'use client';

import React, { useState } from 'react';
import { useStore } from '@/lib/store';
import { useTranslation } from '@/lib/i18n';
import {
  Headphones,
  Ticket,
  Bot,
  UserCircle,
  Bell,
  Globe,
  LogOut,
  Menu,
  X,
  ChevronDown,
  Settings,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Sheet, SheetContent, SheetTrigger, SheetTitle } from '@/components/ui/sheet';
import TicketTracking from './TicketTracking';
import ClientProfile from './ClientProfile';
import ClientAIAgent from './ClientAIAgent';

interface NavItem {
  key: string;
  label: string;
  labelKey: string;
  icon: React.ReactNode;
}

export default function ClientLayout() {
  const currentView = useStore((s) => s.currentView);
  const setView = useStore((s) => s.setView);
  const currentUser = useStore((s) => s.currentUser);
  const logout = useStore((s) => s.logout);
  const language = useStore((s) => s.language);
  const setLanguage = useStore((s) => s.setLanguage);
  const notifications = useStore((s) => s.notifications);
  const markAllNotificationsRead = useStore((s) => s.markAllNotificationsRead);
  const { t } = useTranslation();

  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [notificationsOpen, setNotificationsOpen] = useState(false);

  const navItems: NavItem[] = [
    { key: 'ticket-tracking', label: t.nav.ticketTracking, labelKey: 'ticketTracking', icon: <Ticket className="w-4 h-4" /> },
    { key: 'ai-assistant', label: t.nav.aiAgent, labelKey: 'aiAgent', icon: <Bot className="w-4 h-4" /> },
    { key: 'profile', label: t.nav.profile, labelKey: 'profile', icon: <UserCircle className="w-4 h-4" /> },
  ];

  const unreadCount = notifications.filter((n) => !n.isRead).length;

  const handleNavClick = (view: string) => {
    setView(view);
    setMobileMenuOpen(false);
  };

  const handleLanguageSwitch = () => {
    setLanguage(language === 'en' ? 'bn' : 'en');
  };

  const userInitials = currentUser?.name
    ? currentUser.name
        .split(' ')
        .map((n) => n[0])
        .join('')
        .toUpperCase()
        .slice(0, 2)
    : 'U';

  const renderContent = () => {
    switch (currentView) {
      case 'ticket-tracking':
        return <TicketTracking />;
      case 'ai-assistant':
        return <ClientAIAgent />;
      case 'profile':
        return <ClientProfile />;
      default:
        return <TicketTracking />;
    }
  };

  return (
    <div className="min-h-screen flex flex-col bg-emerald-50/30">
      {/* Top Navigation */}
      <header className="sticky top-0 z-50 bg-white border-b border-emerald-100 shadow-sm">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex items-center justify-between h-16">
            {/* Logo */}
            <div className="flex items-center gap-2.5">
              <div className="flex items-center justify-center w-9 h-9 rounded-lg bg-emerald-500 text-white">
                <Headphones className="w-5 h-5" />
              </div>
              <div className="hidden sm:block">
                <h1 className="text-base font-bold text-emerald-800 leading-tight">
                  {t.common.appName}
                </h1>
                <p className="text-[10px] text-emerald-600/70 leading-tight">
                  {t.portal.clientPortal}
                </p>
              </div>
            </div>

            {/* Desktop Navigation */}
            <nav className="hidden md:flex items-center gap-1">
              {navItems.map((item) => (
                <button
                  key={item.key}
                  onClick={() => handleNavClick(item.key)}
                  className={`flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 ${
                    currentView === item.key
                      ? 'bg-emerald-100 text-emerald-700 shadow-sm'
                      : 'text-gray-600 hover:text-emerald-700 hover:bg-emerald-50'
                  }`}
                >
                  {item.icon}
                  {item.label}
                </button>
              ))}
            </nav>

            {/* Right Section */}
            <div className="flex items-center gap-2">
              {/* Language Switcher */}
              <Button
                variant="ghost"
                size="sm"
                onClick={handleLanguageSwitch}
                className="text-emerald-700 hover:bg-emerald-50 h-9 px-2.5"
              >
                <Globe className="w-4 h-4 mr-1" />
                <span className="text-xs font-semibold">{language === 'en' ? 'BN' : 'EN'}</span>
              </Button>

              {/* Notifications */}
              <DropdownMenu open={notificationsOpen} onOpenChange={setNotificationsOpen}>
                <DropdownMenuTrigger asChild>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="relative text-emerald-700 hover:bg-emerald-50 h-9 w-9 p-0"
                  >
                    <Bell className="w-4.5 h-4.5" />
                    {unreadCount > 0 && (
                      <span className="absolute -top-0.5 -right-0.5 w-4.5 h-4.5 bg-red-500 text-white text-[10px] font-bold rounded-full flex items-center justify-center animate-pulse-green">
                        {unreadCount > 9 ? '9+' : unreadCount}
                      </span>
                    )}
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="w-80">
                  <div className="flex items-center justify-between px-3 py-2 border-b">
                    <span className="font-semibold text-sm">{t.nav.notifications}</span>
                    {unreadCount > 0 && (
                      <Button
                        variant="ghost"
                        size="sm"
                        className="text-xs text-emerald-600 h-7 px-2"
                        onClick={() => markAllNotificationsRead()}
                      >
                        Mark all read
                      </Button>
                    )}
                  </div>
                  <div className="max-h-72 overflow-y-auto">
                    {notifications.length === 0 ? (
                      <div className="p-4 text-center text-sm text-muted-foreground">
                        {t.common.noData}
                      </div>
                    ) : (
                      notifications.slice(0, 10).map((n) => (
                        <DropdownMenuItem key={n.id} className="flex flex-col items-start gap-1 p-3 cursor-pointer">
                          <div className="flex items-center gap-2 w-full">
                            {!n.isRead && (
                              <span className="w-2 h-2 rounded-full bg-emerald-500 flex-shrink-0" />
                            )}
                            <span className="font-medium text-sm truncate">{n.title}</span>
                          </div>
                          <span className="text-xs text-muted-foreground line-clamp-2">{n.message}</span>
                        </DropdownMenuItem>
                      ))
                    )}
                  </div>
                </DropdownMenuContent>
              </DropdownMenu>

              {/* User Avatar Dropdown */}
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button
                    variant="ghost"
                    className="flex items-center gap-2 h-9 px-2 hover:bg-emerald-50"
                  >
                    <Avatar className="w-8 h-8 bg-emerald-100 border-2 border-emerald-200">
                      <AvatarFallback className="bg-emerald-500 text-white text-xs font-bold">
                        {userInitials}
                      </AvatarFallback>
                    </Avatar>
                    <ChevronDown className="w-3.5 h-3.5 text-emerald-600" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="w-56">
                  <div className="px-3 py-2 border-b">
                    <p className="font-semibold text-sm">{currentUser?.name}</p>
                    <p className="text-xs text-muted-foreground">{currentUser?.email}</p>
                  </div>
                  <DropdownMenuItem
                    onClick={() => handleNavClick('profile')}
                    className="cursor-pointer"
                  >
                    <Settings className="w-4 h-4 mr-2" />
                    {t.nav.profile}
                  </DropdownMenuItem>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem
                    onClick={() => logout()}
                    className="cursor-pointer text-red-600 focus:text-red-600"
                  >
                    <LogOut className="w-4 h-4 mr-2" />
                    {t.nav.logout}
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>

              {/* Mobile Menu */}
              <Sheet open={mobileMenuOpen} onOpenChange={setMobileMenuOpen}>
                <SheetTrigger asChild>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="md:hidden text-emerald-700 hover:bg-emerald-50 h-9 w-9 p-0"
                  >
                    <Menu className="w-5 h-5" />
                  </Button>
                </SheetTrigger>
                <SheetContent side="right" className="w-72 p-0">
                  <SheetTitle className="sr-only">Navigation Menu</SheetTitle>
                  <div className="flex flex-col h-full">
                    <div className="flex items-center justify-between p-4 border-b border-emerald-100">
                      <div className="flex items-center gap-2">
                        <div className="flex items-center justify-center w-8 h-8 rounded-lg bg-emerald-500 text-white">
                          <Headphones className="w-4 h-4" />
                        </div>
                        <span className="font-bold text-emerald-800 text-sm">{t.common.appName}</span>
                      </div>
                    </div>
                    <div className="p-3 border-b border-emerald-100">
                      <div className="flex items-center gap-3 p-2">
                        <Avatar className="w-10 h-10 bg-emerald-100 border-2 border-emerald-200">
                          <AvatarFallback className="bg-emerald-500 text-white text-sm font-bold">
                            {userInitials}
                          </AvatarFallback>
                        </Avatar>
                        <div>
                          <p className="font-semibold text-sm">{currentUser?.name}</p>
                          <p className="text-xs text-muted-foreground">{currentUser?.email}</p>
                        </div>
                      </div>
                    </div>
                    <nav className="flex-1 p-3 space-y-1">
                      {navItems.map((item) => (
                        <button
                          key={item.key}
                          onClick={() => handleNavClick(item.key)}
                          className={`flex items-center gap-3 w-full px-3 py-2.5 rounded-lg text-sm font-medium transition-all ${
                            currentView === item.key
                              ? 'bg-emerald-100 text-emerald-700'
                              : 'text-gray-600 hover:text-emerald-700 hover:bg-emerald-50'
                          }`}
                        >
                          {item.icon}
                          {item.label}
                        </button>
                      ))}
                    </nav>
                    <div className="p-3 border-t border-emerald-100 space-y-1">
                      <button
                        onClick={handleLanguageSwitch}
                        className="flex items-center gap-3 w-full px-3 py-2.5 rounded-lg text-sm font-medium text-gray-600 hover:text-emerald-700 hover:bg-emerald-50 transition-all"
                      >
                        <Globe className="w-4 h-4" />
                        {language === 'en' ? 'বাংলা (BN)' : 'English (EN)'}
                      </button>
                      <button
                        onClick={() => logout()}
                        className="flex items-center gap-3 w-full px-3 py-2.5 rounded-lg text-sm font-medium text-red-600 hover:bg-red-50 transition-all"
                      >
                        <LogOut className="w-4 h-4" />
                        {t.nav.logout}
                      </button>
                    </div>
                  </div>
                </SheetContent>
              </Sheet>
            </div>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="flex-1 max-w-7xl mx-auto w-full px-4 sm:px-6 lg:px-8 py-6 pb-20 md:pb-6">
        {renderContent()}
      </main>

      {/* Mobile Bottom Navigation */}
      <nav className="md:hidden fixed bottom-0 left-0 right-0 z-50 bg-white border-t border-emerald-100 shadow-lg safe-area-pb">
        <div className="flex items-center justify-around py-2">
          {navItems.map((item) => (
            <button
              key={item.key}
              onClick={() => handleNavClick(item.key)}
              className={`flex flex-col items-center gap-0.5 px-3 py-1 rounded-lg text-xs font-medium transition-all ${
                currentView === item.key
                  ? 'text-emerald-700'
                  : 'text-gray-400 hover:text-emerald-600'
              }`}
            >
              {item.icon}
              <span className="text-[10px]">{item.label}</span>
            </button>
          ))}
        </div>
      </nav>

      {/* Footer */}
      <footer className="bg-white border-t border-emerald-100 mt-auto">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
          <div className="flex flex-col sm:flex-row items-center justify-between gap-2">
            <div className="flex items-center gap-2">
              <Headphones className="w-4 h-4 text-emerald-500" />
              <span className="text-xs text-muted-foreground">{t.portal.copyright}</span>
            </div>
            <p className="text-xs text-emerald-600/60">{t.portal.tagline}</p>
          </div>
        </div>
      </footer>
    </div>
  );
}
