'use client';

import { useAppStore, type AppSection } from '@/lib/store';
import { t } from '@/lib/i18n';
import { useTheme } from 'next-themes';
import {
  Home,
  Store,
  ShoppingBag,
  Pill,
  GraduationCap,
  Package,
  Users,
  Settings,
  Globe,
  Moon,
  Sun,
  LogOut,
  LogIn,
  Upload,
} from 'lucide-react';
import {
  Sheet,
  SheetContent,
  SheetHeader,
  SheetTitle,
} from '@/components/ui/sheet';
import { Button } from '@/components/ui/button';
import { Switch } from '@/components/ui/switch';
import { Separator } from '@/components/ui/separator';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';

interface SidebarNavItem {
  id: AppSection;
  icon: React.ElementType;
  labelKey: string;
  roles?: string[]; // if specified, only show to users with these roles
}

const mainNavItems: SidebarNavItem[] = [
  { id: 'home', icon: Home, labelKey: 'nav.home' },
  { id: 'house-rental', icon: Home, labelKey: 'sidebar.houseRental' },
  { id: 'shop-rental', icon: Store, labelKey: 'sidebar.shopRental' },
  { id: 'marketplace', icon: ShoppingBag, labelKey: 'sidebar.marketplace' },
  { id: 'medicine', icon: Pill, labelKey: 'sidebar.medicine' },
  { id: 'education', icon: GraduationCap, labelKey: 'sidebar.mcqExam' },
  { id: 'orders', icon: Package, labelKey: 'sidebar.orders' },
  { id: 'community', icon: Users, labelKey: 'sidebar.community' },
];

export default function Sidebar() {
  const {
    sidebarOpen,
    setSidebarOpen,
    currentSection,
    setCurrentSection,
    language,
    setLanguage,
    isLoggedIn,
    user,
    logout,
  } = useAppStore();

  const { theme, setTheme } = useTheme();

  // Check if user has owner roles
  const isHouseOwner = isLoggedIn && user?.roles?.includes('houseOwner');
  const isShopOwner = isLoggedIn && user?.roles?.includes('shopOwner');
  const isOwner = isHouseOwner || isShopOwner;

  const handleNavClick = (section: AppSection) => {
    setCurrentSection(section);
    setSidebarOpen(false);
  };

  const handleLogout = () => {
    logout();
    setSidebarOpen(false);
  };

  const handleLogin = () => {
    setCurrentSection('auth');
    setSidebarOpen(false);
  };

  const getRoleBadge = () => {
    if (!user?.roles) return null;
    if (user.roles.includes('houseOwner') && user.roles.includes('shopOwner')) {
      return (
        <Badge className="bg-primary/10 text-primary text-[9px] px-1.5 py-0">
          {language === 'en' ? 'Owner' : 'মালিক'}
        </Badge>
      );
    }
    if (user.roles.includes('houseOwner')) {
      return (
        <Badge className="bg-amber-100 text-amber-700 dark:bg-amber-950/30 dark:text-amber-400 text-[9px] px-1.5 py-0">
          {language === 'en' ? 'House Owner' : 'বাড়ির মালিক'}
        </Badge>
      );
    }
    if (user.roles.includes('shopOwner')) {
      return (
        <Badge className="bg-orange-100 text-orange-700 dark:bg-orange-950/30 dark:text-orange-400 text-[9px] px-1.5 py-0">
          {language === 'en' ? 'Shop Owner' : 'দোকান মালিক'}
        </Badge>
      );
    }
    return null;
  };

  return (
    <Sheet open={sidebarOpen} onOpenChange={setSidebarOpen}>
      <SheetContent side="left" className="w-[300px] p-0 sm:w-[340px]">
        <SheetHeader className="border-b px-4 py-4">
          {/* User Profile / Login */}
          {isLoggedIn && user ? (
            <div className="flex items-center gap-3">
              <Avatar className="h-11 w-11 border-2 border-primary">
                <AvatarFallback className="bg-primary/10 text-sm font-semibold text-primary">
                  {user.name
                    .split(' ')
                    .map((n) => n[0])
                    .join('')
                    .toUpperCase()
                    .slice(0, 2)}
                </AvatarFallback>
              </Avatar>
              <div className="flex-1 overflow-hidden">
                <div className="flex items-center gap-2">
                  <SheetTitle className="truncate text-base">
                    {user.name}
                  </SheetTitle>
                  {getRoleBadge()}
                </div>
                <p className="truncate text-xs text-muted-foreground">
                  {user.email}
                </p>
              </div>
            </div>
          ) : (
            <div className="flex items-center gap-3">
              <img
                src="/logo-needyfy.png"
                alt="Needyfy Logo"
                className="h-11 w-11 rounded-xl object-cover border-2 border-primary/20"
              />
              <div className="flex-1">
                <SheetTitle className="text-base gradient-text font-bold">
                  {t('app.name', language)}
                </SheetTitle>
                <p className="text-xs text-muted-foreground">
                  {t('app.tagline', language)}
                </p>
              </div>
            </div>
          )}
        </SheetHeader>

        {/* Navigation Items */}
        <div className="flex-1 overflow-y-auto custom-scrollbar">
          <div className="px-2 py-2">
            <p className="mb-1 px-3 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
              {t('nav.explore', language)}
            </p>
            {mainNavItems.map((item) => {
              const Icon = item.icon;
              const isActive = currentSection === item.id;

              return (
                <button
                  key={item.id}
                  onClick={() => handleNavClick(item.id)}
                  className={`flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm transition-colors duration-150 ${
                    isActive
                      ? 'bg-primary/10 font-medium text-primary'
                      : 'text-foreground/80 hover:bg-accent hover:text-foreground'
                  }`}
                >
                  <Icon
                    className={`h-4.5 w-4.5 ${isActive ? 'text-primary' : ''}`}
                    strokeWidth={isActive ? 2.5 : 2}
                  />
                  <span>{t(item.labelKey, language)}</span>
                </button>
              );
            })}
          </div>

          {/* Upload Button for Owners */}
          {isOwner && (
            <>
              <Separator className="my-1" />
              <div className="px-2 py-2">
                <p className="mb-1 px-3 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
                  {language === 'en' ? 'Owner Tools' : 'মালিক টুলস'}
                </p>
                <button
                  onClick={() => handleNavClick('owner-dashboard')}
                  className={`flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm transition-colors duration-150 ${
                    currentSection === 'owner-dashboard'
                      ? 'bg-primary/10 font-medium text-primary'
                      : 'text-foreground/80 hover:bg-accent hover:text-foreground'
                  }`}
                >
                  <Upload
                    className={`h-4.5 w-4.5 ${currentSection === 'owner-dashboard' ? 'text-primary' : ''}`}
                    strokeWidth={currentSection === 'owner-dashboard' ? 2.5 : 2}
                  />
                  <span>{language === 'en' ? 'Upload & Dashboard' : 'আপলোড ও ড্যাশবোর্ড'}</span>
                  <Badge className="ml-auto bg-primary text-primary-foreground text-[9px] px-1.5 py-0">
                    {language === 'en' ? 'New' : 'নতুন'}
                  </Badge>
                </button>
              </div>
            </>
          )}

          <Separator className="my-1" />

          {/* Settings Section */}
          <div className="px-2 py-2">
            <p className="mb-1 px-3 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground">
              {t('sidebar.settings', language)}
            </p>

            {/* Language Toggle */}
            <div className="flex items-center justify-between rounded-lg px-3 py-2.5">
              <div className="flex items-center gap-3 text-sm text-foreground/80">
                <Globe className="h-4.5 w-4.5" />
                <span>{t('sidebar.language', language)}</span>
              </div>
              <Button
                variant="outline"
                size="sm"
                className="h-7 gap-1 px-2 text-xs font-semibold"
                onClick={() => setLanguage(language === 'en' ? 'bn' : 'en')}
              >
                <Globe className="h-3 w-3" />
                {language === 'en' ? 'BN' : 'EN'}
              </Button>
            </div>

            {/* Dark Mode Toggle */}
            <div className="flex items-center justify-between rounded-lg px-3 py-2.5">
              <div className="flex items-center gap-3 text-sm text-foreground/80">
                {theme === 'dark' ? (
                  <Sun className="h-4.5 w-4.5" />
                ) : (
                  <Moon className="h-4.5 w-4.5" />
                )}
                <span>{t('sidebar.darkMode', language)}</span>
              </div>
              <Switch
                checked={theme === 'dark'}
                onCheckedChange={(checked) =>
                  setTheme(checked ? 'dark' : 'light')
                }
                aria-label={t('sidebar.darkMode', language)}
              />
            </div>
          </div>

          <Separator className="my-1" />

          {/* Auth Actions */}
          <div className="px-2 py-2">
            {isLoggedIn ? (
              <button
                onClick={handleLogout}
                className="flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm text-destructive transition-colors duration-150 hover:bg-destructive/10"
              >
                <LogOut className="h-4.5 w-4.5" />
                <span>{t('profile.logout', language)}</span>
              </button>
            ) : (
              <button
                onClick={handleLogin}
                className="flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm text-primary transition-colors duration-150 hover:bg-primary/10"
              >
                <LogIn className="h-4.5 w-4.5" />
                <span>{t('profile.login', language)}</span>
              </button>
            )}
          </div>
        </div>

        {/* Footer */}
        <div className="border-t px-4 py-3">
          <p className="text-center text-[10px] text-muted-foreground">
            {t('app.name', language)} &middot; {t('app.motto', language)}
          </p>
        </div>
      </SheetContent>
    </Sheet>
  );
}
