'use client';

import { Shield, Search, Menu, X, User, Moon, Sun, LayoutDashboard, ShieldAlert, Brain, LogOut, Bell, UserCircle, CheckCircle, AlertTriangle, TrendingUp, MessageSquare, Languages, ShieldCheck } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useAppStore } from '@/store/app-store';
import { useLangStore } from '@/store/lang-store';
import { useTheme } from 'next-themes';
import { useState, useCallback, useSyncExternalStore } from 'react';
import type { Page } from '@/types';
import { motion, AnimatePresence } from 'framer-motion';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { ScrollArea } from '@/components/ui/scroll-area';

const emptySubscribe = () => () => {};

const navKeys: { labelKey: string; page: Page; icon: React.ElementType }[] = [
  { labelKey: 'nav.home', page: 'home', icon: Shield },
  { labelKey: 'nav.search', page: 'search', icon: Search },
  { labelKey: 'nav.checkNumber', page: 'check-number', icon: ShieldCheck },
  { labelKey: 'nav.report', page: 'report', icon: ShieldAlert },
  { labelKey: 'nav.analytics', page: 'analytics', icon: LayoutDashboard },
  { labelKey: 'nav.aiDetect', page: 'ai-detect', icon: Brain },
];

export function Header() {
  const navigate = useAppStore((s) => s.navigate);
  const currentPage = useAppStore((s) => s.currentPage);
  const user = useAppStore((s) => s.user);
  const setUser = useAppStore((s) => s.setUser);
  const setSearchQuery = useAppStore((s) => s.setSearchQuery);
  const { theme, setTheme } = useTheme();
  const { lang, toggleLang, t } = useLangStore();
  const [mobileOpen, setMobileOpen] = useState(false);
  const [searchInput, setSearchInput] = useState('');
  const mounted = useSyncExternalStore(emptySubscribe, () => true, () => false);

  const handleLogout = useCallback(() => {
    localStorage.removeItem('scamchecker_user');
    setUser(null);
    navigate('home');
  }, [setUser, navigate]);

  const handleSearch = useCallback(() => {
    if (searchInput.trim()) {
      setSearchQuery(searchInput.trim());
      navigate('check-number');
    }
  }, [searchInput, setSearchQuery, navigate]);

  const toggleTheme = useCallback(() => {
    setTheme(theme === 'dark' ? 'light' : 'dark');
  }, [theme, setTheme]);

  return (
    <header className="sticky top-0 z-50 glass border-b">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex items-center justify-between h-14">
          {/* Logo */}
          <button
            onClick={() => navigate('home')}
            className="flex items-center gap-2 hover:opacity-80 transition-opacity shrink-0"
          >
            <motion.div
              animate={{
                filter: [
                  'drop-shadow(0 0 6px oklch(0.558 0.158 155 / 0.3))',
                  'drop-shadow(0 0 14px oklch(0.558 0.158 155 / 0.5))',
                  'drop-shadow(0 0 6px oklch(0.558 0.158 155 / 0.3))',
                ],
              }}
              transition={{ duration: 3, repeat: Infinity, ease: 'easeInOut' }}
            >
              <Shield className="h-6 w-6 text-emerald-500" />
            </motion.div>
            <span className="font-bold text-lg hidden sm:inline">
              Scam<span className="text-emerald-500">Checker</span> BD
            </span>
          </button>

          {/* Desktop nav */}
          <nav className="hidden lg:flex items-center gap-0.5">
            {navKeys.map((item) => (
              <Button
                key={item.page}
                variant="ghost"
                size="sm"
                onClick={() => navigate(item.page)}
                className={`relative text-sm ${
                  currentPage === item.page
                    ? 'text-emerald-500 font-semibold'
                    : 'text-muted-foreground hover:text-foreground'
                }`}
              >
                {currentPage === item.page && (
                  <motion.div
                    layoutId="activeNav"
                    className="absolute inset-0 bg-emerald-500/10 rounded-md"
                    transition={{ type: 'spring', bounce: 0.2, duration: 0.6 }}
                  />
                )}
                <span className="relative z-10">{t(item.labelKey)}</span>
              </Button>
            ))}
          </nav>

          {/* Desktop search + actions */}
          <div className="hidden md:flex items-center gap-2">
            {/* Search bar */}
            <div className="relative">
              <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
              <Input
                type="text"
                placeholder={t('nav.quickSearch')}
                value={searchInput}
                onChange={(e) => setSearchInput(e.target.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                className="h-8 w-44 pl-8 text-sm rounded-lg bg-muted/50 border-transparent focus:border-emerald-500/30 focus:bg-background"
              />
            </div>

            {/* Theme toggle */}
            {mounted && (
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8"
                onClick={toggleTheme}
              >
                <AnimatePresence mode="wait" initial={false}>
                  {theme === 'dark' ? (
                    <motion.div
                      key="sun"
                      initial={{ rotate: -90, scale: 0 }}
                      animate={{ rotate: 0, scale: 1 }}
                      exit={{ rotate: 90, scale: 0 }}
                      transition={{ duration: 0.2 }}
                    >
                      <Sun className="h-4 w-4" />
                    </motion.div>
                  ) : (
                    <motion.div
                      key="moon"
                      initial={{ rotate: 90, scale: 0 }}
                      animate={{ rotate: 0, scale: 1 }}
                      exit={{ rotate: -90, scale: 0 }}
                      transition={{ duration: 0.2 }}
                    >
                      <Moon className="h-4 w-4" />
                    </motion.div>
                  )}
                </AnimatePresence>
              </Button>
            )}

            {/* Language toggle */}
            <Button
              variant="ghost"
              size="sm"
              className="h-8 px-2 text-xs font-semibold gap-1 hover:bg-emerald-500/10 hover:text-emerald-500"
              onClick={toggleLang}
            >
              <Languages className="h-3.5 w-3.5" />
              {lang === 'en' ? 'বাং' : 'EN'}
            </Button>

            {/* Notification Bell */}
            {user && <NotificationCenter />}

            {/* User section */}
            {user ? (
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" size="sm" className="gap-1.5 h-8">
                    <Avatar className="h-6 w-6">
                      <AvatarFallback className="bg-emerald-500/20 text-emerald-500 text-xs">
                        {(user.name || user.email)[0].toUpperCase()}
                      </AvatarFallback>
                    </Avatar>
                    <span className="text-sm max-w-20 truncate">{user.name || user.email}</span>
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="w-48">
                  <DropdownMenuItem onClick={() => navigate('dashboard')}>
                    <LayoutDashboard className="h-4 w-4 mr-2" />
                    {t('nav.dashboard')}
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => navigate('profile')}>
                    <UserCircle className="h-4 w-4 mr-2" />
                    {t('nav.profile')}
                  </DropdownMenuItem>
                  {user.role === 'admin' && (
                    <DropdownMenuItem onClick={() => navigate('admin')}>
                      <ShieldAlert className="h-4 w-4 mr-2" />
                      {t('nav.adminPanel')}
                    </DropdownMenuItem>
                  )}
                  <DropdownMenuSeparator />
                  <DropdownMenuItem onClick={handleLogout} className="text-red-500">
                    <LogOut className="h-4 w-4 mr-2" />
                    {t('nav.logout')}
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            ) : (
              <div className="flex items-center gap-1.5">
                <Button variant="ghost" size="sm" onClick={() => navigate('login')} className="text-sm h-8">
                  {t('nav.login')}
                </Button>
                <Button
                  size="sm"
                  onClick={() => navigate('register')}
                  className="bg-emerald-600 hover:bg-emerald-700 text-sm h-8"
                >
                  {t('nav.register')}
                </Button>
              </div>
            )}
          </div>

          {/* Mobile toggle */}
          <Button
            variant="ghost"
            size="icon"
            className="md:hidden h-8 w-8"
            onClick={() => setMobileOpen(!mobileOpen)}
          >
            {mobileOpen ? <X className="h-5 w-5" /> : <Menu className="h-5 w-5" />}
          </Button>
        </div>

        {/* Mobile nav */}
        <AnimatePresence>
          {mobileOpen && (
            <motion.div
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              className="md:hidden border-t overflow-hidden"
            >
              <div className="py-3 space-y-1">
                {/* Mobile search */}
                <div className="relative mb-2 px-1">
                  <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <Input
                    type="text"
                    placeholder={t('nav.quickSearch')}
                    value={searchInput}
                    onChange={(e) => setSearchInput(e.target.value)}
                    onKeyDown={(e) => {
                      if (e.key === 'Enter') {
                        handleSearch();
                        setMobileOpen(false);
                      }
                    }}
                    className="h-9 pl-10 text-sm"
                  />
                </div>

                {navKeys.map((item) => (
                  <Button
                    key={item.page}
                    variant={currentPage === item.page ? 'secondary' : 'ghost'}
                    size="sm"
                    className={`w-full justify-start gap-2 ${
                      currentPage === item.page ? 'text-emerald-500' : ''
                    }`}
                    onClick={() => {
                      navigate(item.page);
                      setMobileOpen(false);
                    }}
                  >
                    <item.icon className="h-4 w-4" />
                    {t(item.labelKey)}
                  </Button>
                ))}

                <div className="border-t pt-2 mt-2">
                  {user ? (
                    <>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="w-full justify-start gap-2"
                        onClick={() => {
                          navigate('dashboard');
                          setMobileOpen(false);
                        }}
                      >
                        <LayoutDashboard className="h-4 w-4" />
                        {t('nav.dashboard')}
                      </Button>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="w-full justify-start gap-2"
                        onClick={() => {
                          navigate('profile');
                          setMobileOpen(false);
                        }}
                      >
                        <UserCircle className="h-4 w-4" />
                        {t('nav.profile')}
                      </Button>
                      {user.role === 'admin' && (
                        <Button
                          variant="ghost"
                          size="sm"
                          className="w-full justify-start gap-2"
                          onClick={() => {
                            navigate('admin');
                            setMobileOpen(false);
                          }}
                        >
                          <ShieldAlert className="h-4 w-4" />
                          {t('nav.adminPanel')}
                        </Button>
                      )}
                      <Button
                        variant="ghost"
                        size="sm"
                        className="w-full justify-start gap-2 text-red-500"
                        onClick={() => {
                          handleLogout();
                          setMobileOpen(false);
                        }}
                      >
                        <LogOut className="h-4 w-4" />
                        {t('nav.logout')}
                      </Button>
                    </>
                  ) : (
                    <>
                      <Button
                        variant="ghost"
                        size="sm"
                        className="w-full justify-start"
                        onClick={() => {
                          navigate('login');
                          setMobileOpen(false);
                        }}
                      >
                        {t('nav.login')}
                      </Button>
                      <Button
                        size="sm"
                        className="w-full justify-start bg-emerald-600 hover:bg-emerald-700"
                        onClick={() => {
                          navigate('register');
                          setMobileOpen(false);
                        }}
                      >
                        {t('nav.register')}
                      </Button>
                    </>
                  )}
                </div>

                {/* Mobile theme toggle & language toggle */}
                <div className="border-t pt-2 mt-2 px-1 space-y-1">
                  <Button
                    variant="ghost"
                    size="sm"
                    className="w-full justify-start gap-2"
                    onClick={() => {
                      toggleTheme();
                      setMobileOpen(false);
                    }}
                  >
                    {mounted && theme === 'dark' ? (
                      <><Sun className="h-4 w-4" /> Light Mode</>
                    ) : (
                      <><Moon className="h-4 w-4" /> Dark Mode</>
                    )}
                  </Button>
                  <Button
                    variant="ghost"
                    size="sm"
                    className="w-full justify-start gap-2"
                    onClick={() => {
                      toggleLang();
                      setMobileOpen(false);
                    }}
                  >
                    <Languages className="h-4 w-4" />
                    {lang === 'en' ? 'বাংলায় দেখুন' : 'View in English'}
                  </Button>
                </div>
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>
    </header>
  );
}

// ─── Notification Center Component ────────────────────────────────────────

interface Notification {
  id: string;
  title: string;
  description: string;
  time: string;
  icon: React.ElementType;
  iconColor: string;
  iconBg: string;
  read: boolean;
}

const simulatedNotifications: Notification[] = [
  {
    id: '1',
    title: 'Report Verified',
    description: 'Your scam report "Fake bKash Agent" has been verified by our team.',
    time: '5m ago',
    icon: CheckCircle,
    iconColor: 'text-emerald-500',
    iconBg: 'bg-emerald-500/10',
    read: false,
  },
  {
    id: '2',
    title: 'New Report in Your District',
    description: 'A new scam report was filed in Dhaka district.',
    time: '1h ago',
    icon: AlertTriangle,
    iconColor: 'text-yellow-500',
    iconBg: 'bg-yellow-500/10',
    read: false,
  },
  {
    id: '3',
    title: 'Upvote Milestone',
    description: 'Your report received 10 upvotes! Keep helping the community.',
    time: '3h ago',
    icon: TrendingUp,
    iconColor: 'text-cyan-500',
    iconBg: 'bg-cyan-500/10',
    read: false,
  },
  {
    id: '4',
    title: 'New Comment',
    description: 'Someone commented on your report "Online Shopping Fraud".',
    time: '6h ago',
    icon: MessageSquare,
    iconColor: 'text-teal-500',
    iconBg: 'bg-teal-500/10',
    read: true,
  },
  {
    id: '5',
    title: 'Weekly Summary',
    description: '15 new scams reported this week in your area. Stay alert!',
    time: '1d ago',
    icon: Shield,
    iconColor: 'text-emerald-500',
    iconBg: 'bg-emerald-500/10',
    read: true,
  },
];

function NotificationCenter() {
  const [notifications, setNotifications] = useState<Notification[]>(simulatedNotifications);
  const unreadCount = notifications.filter((n) => !n.read).length;

  const markAllRead = useCallback(() => {
    setNotifications((prev) => prev.map((n) => ({ ...n, read: true })));
  }, []);

  return (
    <Popover>
      <PopoverTrigger asChild>
        <Button variant="ghost" size="icon" className="h-8 w-8 relative">
          <Bell className="h-4 w-4" />
          {unreadCount > 0 && (
            <span className="absolute -top-0.5 -right-0.5 flex h-4 w-4 items-center justify-center rounded-full bg-emerald-500 text-[10px] font-bold text-white">
              {unreadCount}
            </span>
          )}
        </Button>
      </PopoverTrigger>
      <PopoverContent align="end" className="w-80 p-0">
        <div className="flex items-center justify-between p-3 border-b">
          <h3 className="font-semibold text-sm">Notifications</h3>
          {unreadCount > 0 && (
            <Button
              variant="ghost"
              size="sm"
              className="text-xs h-6 px-2 text-emerald-600 dark:text-emerald-400"
              onClick={markAllRead}
            >
              Mark all read
            </Button>
          )}
        </div>
        <ScrollArea className="max-h-80">
          {notifications.length === 0 ? (
            <div className="p-6 text-center text-sm text-muted-foreground">
              No notifications yet
            </div>
          ) : (
            <div>
              {notifications.map((notification) => {
                const NotifIcon = notification.icon;
                return (
                  <div
                    key={notification.id}
                    className={`flex items-start gap-3 p-3 border-b last:border-b-0 hover:bg-muted/50 transition-colors ${
                      !notification.read ? 'bg-emerald-500/5' : ''
                    }`}
                  >
                    <div className={`p-1.5 rounded-lg ${notification.iconBg} shrink-0 mt-0.5`}>
                      <NotifIcon className={`h-3.5 w-3.5 ${notification.iconColor}`} />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <p className="text-sm font-medium truncate">{notification.title}</p>
                        {!notification.read && (
                          <span className="h-2 w-2 rounded-full bg-emerald-500 shrink-0" />
                        )}
                      </div>
                      <p className="text-xs text-muted-foreground line-clamp-2 mt-0.5">
                        {notification.description}
                      </p>
                      <p className="text-[10px] text-muted-foreground mt-1">{notification.time}</p>
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </ScrollArea>
      </PopoverContent>
    </Popover>
  );
}
