'use client';

import { useRouter } from '@/shared/config/i18n/navigation';
import { useCartId } from '@/shared/hooks/cartId';
import { removeRefToken, removeToken } from '@/shared/lib/token';
import { Avatar, AvatarFallback, AvatarImage } from '@/shared/ui/avatar';
import { Button } from '@/shared/ui/button';
import { banner_api } from '@/widgets/welcome/lib/api';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { Headset, Home, LogOut } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { useEffect, useState } from 'react';
import HistoryTabs from './History';

const Profile = () => {
  const [activeSection, setActiveSection] = useState('overview');
  const router = useRouter();
  const t = useTranslations();
  const queryClient = useQueryClient();

  const { data: me, isError } = useQuery({
    queryKey: ['get_me'],
    queryFn: () => banner_api.getMe(),
    select(data) {
      return data.data;
    },
  });

  useEffect(() => {
    if (isError) {
      router.replace('/');
    }
  }, [isError]);

  const { setCartId } = useCartId();

  const menuItems = [
    { id: 'overview', label: 'Umumiy', icon: Home },
    { id: 'support', label: "Qo'llab-quvatlash", icon: Headset },
  ];

  const renderContent = () => {
    switch (activeSection) {
      case 'support':
        router.push('https://t.me/web_app_0515_bot');

      default:
        return <HistoryTabs />;
    }
  };

  return (
    <div className="custom-container">
      <div className="md:hidden sticky top-0 z-20 mb-5">
        <div className="flex gap-2 overflow-x-auto scrollbar-hide">
          {menuItems.map((item) => {
            const Icon = item.icon;
            return (
              <button
                key={item.id}
                onClick={() => setActiveSection(item.id)}
                className={`flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition-colors ${
                  activeSection === item.id
                    ? 'bg-emerald-500 text-white'
                    : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
                }`}
              >
                <Icon className="w-4 h-4" />
                {t(item.label)}
              </button>
            );
          })}
        </div>
      </div>

      <div>
        <div className="flex gap-4 md:gap-6">
          {/* Desktop Sidebar - hidden on mobile */}
          <div className="hidden lg:block w-80 shrink-0">
            <div className="flex items-center gap-4 mb-8">
              <Avatar className="w-14 h-14 ring-2 ring-emerald-500 ring-offset-2 flex items-center justify-center">
                <AvatarImage />
                <AvatarFallback className="text-muted-foreground font-semibold">
                  {me?.first_name.slice(0, 1).toUpperCase()}
                </AvatarFallback>
              </Avatar>
              <div>
                <p className="text-lg text-muted-foreground font-medium">
                  {me &&
                    me.first_name.charAt(0).toUpperCase() +
                      me.first_name.slice(1)}
                </p>
              </div>
            </div>

            {/* Navigation */}
            <nav className="flex-1 space-y-1">
              {menuItems.map((item) => (
                <button
                  key={item.id}
                  onClick={() => setActiveSection(item.id)}
                  className={`w-full flex items-center gap-3 px-4 py-3 rounded-xl text-left transition-all ${
                    activeSection === item.id
                      ? 'bg-emerald-50 text-emerald-600 font-medium'
                      : 'text-muted-foreground hover:bg-slate-50 hover:text-foreground'
                  }`}
                >
                  <item.icon className="w-5 h-5" />
                  {t(item.label)}
                </button>
              ))}
            </nav>

            {/* Logout */}
            <Button
              variant="ghost"
              onClick={() => {
                queryClient.refetchQueries();
                setCartId(null);
                removeToken();
                removeRefToken();
                router.push('/');
              }}
              className="w-full justify-start gap-3 text-red-500 hover:text-red-600 hover:bg-red-50 mt-4"
            >
              <LogOut className="w-5 h-5" />
              {t('Chiqish')}
            </Button>
          </div>

          {/* Main Content */}
          <main className="flex-1 md:p-4 lg:p-8 lg:pb-8">
            <div className="lg:hidden flex items-center justify-between mb-4 md:mb-6">
              <div className="flex items-center gap-2 md:gap-3">
                <Avatar className="w-10 h-10 md:w-12 md:h-12 ring-2 ring-emerald-500 ring-offset-2">
                  <AvatarImage />
                  <AvatarFallback className="text-muted-foreground font-semibold">
                    {me?.first_name?.slice(0, 1).toUpperCase()}
                  </AvatarFallback>
                </Avatar>
                <div>
                  <p className="text-md md:text-xl text-muted-foreground">
                    {me &&
                      me.first_name.charAt(0).toUpperCase() +
                        me.first_name.slice(1)}
                  </p>
                </div>
              </div>
              <Button
                variant="ghost"
                size="icon"
                onClick={() => {
                  queryClient.refetchQueries();
                  removeToken();
                  removeRefToken();
                  router.push('/');
                }}
                className="w-9 h-9 md:w-10 md:h-10"
              >
                <LogOut className="w-4 text-red-500 h-4 md:w-5 md:h-5" />
              </Button>
            </div>

            {renderContent()}
          </main>
        </div>
      </div>
    </div>
  );
};

export default Profile;
