'use client';

import { useState, useRef, useEffect, useCallback } from 'react';
import { useAppStore } from '@/lib/store';
import { t } from '@/lib/i18n';
import { useTheme } from 'next-themes';
import {
  Search,
  Bell,
  Menu,
  Sun,
  Moon,
  Globe,
  X,
  Home,
  ShoppingBag,
  GraduationCap,
  Package,
  Shield,
  Info,
  CheckCheck,
} from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Separator } from '@/components/ui/separator';
import type { NotificationType, AppSection } from '@/lib/store';

const notifIconMap: Record<NotificationType, React.ElementType> = {
  house: Home,
  product: ShoppingBag,
  mcq: GraduationCap,
  order: Package,
  admin: Shield,
  system: Info,
};

const notifColorMap: Record<NotificationType, string> = {
  house: 'bg-emerald-100 text-emerald-600 dark:bg-emerald-900/40 dark:text-emerald-400',
  product: 'bg-orange-100 text-orange-600 dark:bg-orange-900/40 dark:text-orange-400',
  mcq: 'bg-orange-100 text-orange-600 dark:bg-orange-900/40 dark:text-orange-400',
  order: 'bg-amber-100 text-amber-600 dark:bg-amber-900/40 dark:text-amber-400',
  admin: 'bg-rose-100 text-rose-600 dark:bg-rose-900/40 dark:text-rose-400',
  system: 'bg-slate-100 text-slate-600 dark:bg-slate-800/40 dark:text-slate-400',
};

const notifSectionMap: Record<NotificationType, AppSection> = {
  house: 'house-rental',
  product: 'marketplace',
  mcq: 'education',
  order: 'orders',
  admin: 'settings',
  system: 'settings',
};

export default function Header() {
  const {
    language,
    setLanguage,
    notifications,
    markAsRead,
    markAllAsRead,
    unreadNotifications,
    searchQuery,
    setSearchQuery,
    setSidebarOpen,
    setCurrentSection,
  } = useAppStore();

  const { theme, setTheme } = useTheme();
  const [searchExpanded, setSearchExpanded] = useState(false);
  const [notifOpen, setNotifOpen] = useState(false);
  const [notifPosition, setNotifPosition] = useState<{ top: number; right: number; isMobile: boolean } | null>(null);
  const notifRef = useRef<HTMLDivElement>(null);
  const notifButtonRef = useRef<HTMLButtonElement>(null);

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

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

  const handleNotifToggle = () => {
    if (!notifOpen && notifButtonRef.current) {
      const rect = notifButtonRef.current.getBoundingClientRect();
      const isMobile = window.innerWidth < 640;
      setNotifPosition({
        top: rect.bottom + 8,
        right: isMobile ? 16 : window.innerWidth - rect.right,
        isMobile,
      });
    }
    setNotifOpen((prev) => !prev);
  };

  const handleClickOutside = useCallback((e: MouseEvent) => {
    if (
      notifRef.current &&
      !notifRef.current.contains(e.target as Node) &&
      notifButtonRef.current &&
      !notifButtonRef.current.contains(e.target as Node)
    ) {
      setNotifOpen(false);
    }
  }, []);

  useEffect(() => {
    if (notifOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [notifOpen, handleClickOutside]);

  return (
    <header className="sticky top-0 z-40 w-full border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
      <div className="flex h-14 items-center gap-2 px-3 sm:px-4">
        {/* Hamburger Menu */}
        <Button
          variant="ghost"
          size="icon"
          className="shrink-0 md:hidden"
          onClick={() => setSidebarOpen(true)}
          aria-label="Open menu"
        >
          <Menu className="h-5 w-5" />
        </Button>

        {/* Logo */}
        <div className="flex shrink-0 items-center gap-2">
          <img
            src="/logo-needyfy.png"
            alt="Needyfy Logo"
            className="h-8 w-8 rounded-lg object-cover sm:h-9 sm:w-9"
          />
          <h1 className="gradient-text text-xl font-bold tracking-tight sm:text-2xl">
            {t('app.name', language)}
          </h1>
        </div>

        {/* Search Bar - Desktop */}
        <div className="mx-3 hidden flex-1 md:flex">
          <div className="relative w-full max-w-md">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <Input
              type="text"
              placeholder={t('home.search', language)}
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="h-9 pl-9 pr-4"
            />
          </div>
        </div>

        {/* Search Icon - Mobile (expandable) */}
        <div className="flex flex-1 items-center justify-end gap-1 md:hidden">
          {searchExpanded ? (
            <div className="flex flex-1 items-center gap-1">
              <div className="relative flex-1">
                <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
                <Input
                  type="text"
                  placeholder={t('common.search', language)}
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="h-9 pl-9 pr-4"
                  autoFocus
                />
              </div>
              <Button
                variant="ghost"
                size="icon"
                className="h-9 w-9 shrink-0"
                onClick={() => {
                  setSearchExpanded(false);
                  setSearchQuery('');
                }}
                aria-label="Close search"
              >
                <X className="h-4 w-4" />
              </Button>
            </div>
          ) : (
            <Button
              variant="ghost"
              size="icon"
              className="h-9 w-9 shrink-0"
              onClick={() => setSearchExpanded(true)}
              aria-label="Open search"
            >
              <Search className="h-5 w-5" />
            </Button>
          )}
        </div>

        {/* Right Actions - Hidden on mobile when search is expanded */}
        <div
          className={`flex items-center gap-1 ${
            searchExpanded ? 'hidden md:flex' : 'flex'
          }`}
        >
          {/* Notifications */}
          <div className="relative z-50">
            <Button
              ref={notifButtonRef}
              variant="ghost"
              size="icon"
              className="relative h-9 w-9 shrink-0"
              onClick={handleNotifToggle}
              aria-label={t('notif.title', language)}
              aria-expanded={notifOpen}
            >
              <Bell className={`h-5 w-5 ${notifOpen ? 'text-primary' : ''}`} />
              {unreadNotifications > 0 && (
                <Badge
                  variant="destructive"
                  className="absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[10px] font-bold"
                >
                  {unreadNotifications > 99 ? '99+' : unreadNotifications}
                </Badge>
              )}
            </Button>

            {/* Notification Dropdown Panel */}
            {notifOpen && (
              <div
                ref={notifRef}
                className="fixed z-[100] flex max-h-[70vh] flex-col overflow-hidden rounded-lg border bg-popover shadow-lg animate-in fade-in-0 zoom-in-95 slide-in-from-top-2"
                style={{
                  top: notifPosition?.top ?? 'auto',
                  right: notifPosition?.right ?? 0,
                  ...(notifPosition?.isMobile ? { left: '1rem' } : { maxWidth: '360px' }),
                  minWidth: '280px',
                  maxHeight: `min(70vh, calc(100vh - ${(notifPosition?.top ?? 60) + 16}px))`,
                }}
                role="dialog"
                aria-label={t('notif.title', language)}
              >
                {/* Header */}
                <div className="flex shrink-0 items-center justify-between px-4 py-3">
                  <div className="flex items-center gap-2">
                    <h3 className="text-sm font-semibold">
                      {t('notif.title', language)}
                    </h3>
                    {unreadNotifications > 0 && (
                      <Badge variant="secondary" className="text-[10px] px-1.5 py-0">
                        {unreadNotifications} {t('notif.new', language)}
                      </Badge>
                    )}
                  </div>
                  {unreadNotifications > 0 && (
                    <Button
                      variant="ghost"
                      size="sm"
                      className="h-7 gap-1 px-2 text-xs text-muted-foreground hover:text-foreground"
                      onClick={() => markAllAsRead()}
                    >
                      <CheckCheck className="h-3.5 w-3.5" />
                      {t('notif.markAllRead', language)}
                    </Button>
                  )}
                </div>

                <Separator className="shrink-0" />

                {/* Scrollable Notification List */}
                <div className="custom-scrollbar flex-1 overflow-y-auto overscroll-contain" style={{ WebkitOverflowScrolling: 'touch' }}>
                  <div className="py-1">
                    {notifications.length === 0 ? (
                      <div className="flex flex-col items-center justify-center py-8 text-muted-foreground">
                        <Bell className="mb-2 h-8 w-8 opacity-40" />
                        <p className="text-sm">{t('notif.empty', language)}</p>
                      </div>
                    ) : (
                      notifications.map((notification) => {
                        const Icon = notifIconMap[notification.type];
                        const colorClass = notifColorMap[notification.type];
                        return (
                          <button
                            key={notification.id}
                            className={`flex w-full items-start gap-3 px-4 py-3 text-left transition-colors hover:bg-accent/50 ${
                              !notification.isRead ? 'bg-accent/30' : ''
                            }`}
                            onClick={() => {
                              markAsRead(notification.id);
                              setCurrentSection(notifSectionMap[notification.type]);
                              setNotifOpen(false);
                            }}
                          >
                            {/* Icon */}
                            <div
                              className={`mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full ${colorClass}`}
                            >
                              <Icon className="h-4 w-4" />
                            </div>

                            {/* Content */}
                            <div className="min-w-0 flex-1">
                              <div className="flex items-center gap-2">
                                <p
                                  className={`truncate text-sm ${
                                    !notification.isRead
                                      ? 'font-semibold'
                                      : 'font-medium'
                                  }`}
                                >
                                  {notification.title}
                                </p>
                                {!notification.isRead && (
                                  <span className="h-2 w-2 shrink-0 rounded-full bg-primary" />
                                )}
                              </div>
                              <p className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">
                                {notification.message}
                              </p>
                              <p className="mt-1 text-[11px] text-muted-foreground/70">
                                {notification.time}
                              </p>
                            </div>
                          </button>
                        );
                      })
                    )}
                  </div>
                </div>

                <Separator className="shrink-0" />

                {/* Footer */}
                <div className="shrink-0 p-2">
                  <Button
                    variant="ghost"
                    className="w-full justify-center text-xs font-medium text-muted-foreground hover:text-foreground"
                    size="sm"
                    onClick={() => setNotifOpen(false)}
                  >
                    {t('notif.viewAll', language)}
                  </Button>
                </div>
              </div>
            )}
          </div>

          {/* Dark Mode Toggle */}
          <Button
            variant="ghost"
            size="icon"
            className="h-9 w-9 shrink-0"
            onClick={toggleTheme}
            aria-label="Toggle theme"
          >
            {theme === 'dark' ? (
              <Sun className="h-5 w-5" />
            ) : (
              <Moon className="h-5 w-5" />
            )}
          </Button>

          {/* Language Toggle */}
          <Button
            variant="ghost"
            size="sm"
            className="h-9 shrink-0 gap-1 px-2 text-xs font-semibold"
            onClick={toggleLanguage}
            aria-label="Toggle language"
          >
            <Globe className="h-4 w-4" />
            <span className="uppercase">{language}</span>
          </Button>
        </div>
      </div>
    </header>
  );
}
