'use client';

import Link from 'next/link';
import { useRouter, usePathname } from 'next/navigation';
import {
  Search,
  Globe,
  Bell,
  Bookmark,
  Home,
  ShoppingBag,
  MessagesSquare,
  HeadphonesIcon,
  CheckCircle2, ChevronRight, CreditCard, Gift, Info, Settings
} from 'lucide-react';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { useTranslations } from 'next-intl';
import { useAuthStore } from '@/store/authStore';
import { api } from '@/lib/api';
import { fetchSiteConfig } from '@/lib/siteConfig';

import UserDropdown from '@/components/UserDropdown';

export default function Navbar() {
  const t = useTranslations('Auth');
  const router = useRouter();
  const pathname = usePathname();
  const token = useAuthStore((s) => s.token);
  const [query, setQuery] = useState('');
  const [siteName, setSiteName] = useState('SHOP MMO');
  const [primaryColor, setPrimaryColor] = useState('#ef4444');
  const [unreadNotifications, setUnreadNotifications] = useState(0);
  const [notificationsOpen, setNotificationsOpen] = useState(false);
  const [notifications, setNotifications] = useState<any[]>([]);
  const [notificationFilter, setNotificationFilter] = useState<'ALL' | 'TRANSACTION' | 'SYSTEM' | 'PROMOTION'>('ALL');

  const currentLocale = pathname.startsWith('/en') ? 'en' : 'vi';

  useEffect(() => {
    const loadSettings = async () => {
      try {
        const config = await fetchSiteConfig(currentLocale);
        setSiteName(config.siteName || 'SHOP MMO');
        setPrimaryColor(config.primaryColor || '#ef4444');
      } catch {
        // Keep defaults when backend is unavailable
      }
    };

    loadSettings();
  }, [currentLocale]);

  useEffect(() => {
    if (!token) return;
    const loadUnread = () => api.get('/notifications/unread-summary').then((response) => setUnreadNotifications(response.data.total || 0)).catch(() => undefined);
    void loadUnread();
    const interval = window.setInterval(loadUnread, 30000);
    return () => window.clearInterval(interval);
  }, [token]);

  const readNotifications = async () => {
    if (!unreadNotifications) return;
    await api.post('/notifications/read-all');
    setUnreadNotifications(0);
    setNotifications((items) => items.map((item) => ({ ...item, isRead: true })));
  };

  const loadNotifications = async () => {
    try { const response = await api.get('/notifications', { params: { limit: 30 } }); setNotifications(response.data || []); } catch { setNotifications([]); }
  };
  const toggleNotifications = async () => {
    const next = !notificationsOpen;
    setNotificationsOpen(next);
    if (next) await loadNotifications();
  };
  const category = (type: string) => {
    if (['PAYMENT', 'ESCROW', 'REFUND', 'WITHDRAWAL', 'ORDER_CHAT'].includes(type)) return 'TRANSACTION';
    if (type === 'PROMOTION') return 'PROMOTION';
    return 'SYSTEM';
  };
  const notificationHref = (type: string) => {
    if (type === 'ORDER_CHAT' || ['PAYMENT', 'ESCROW', 'REFUND'].includes(type)) return `/${currentLocale}/orders`;
    if (type.includes('WITHDRAW')) return `/${currentLocale}/seller/withdraw`;
    return `/${currentLocale}/profile`;
  };
  const openNotification = async (note: any) => {
    if (!note.isRead) { await api.post(`/notifications/${note.id}/read`); setUnreadNotifications((value) => Math.max(0, value - 1)); setNotifications((items) => items.map((item) => item.id === note.id ? { ...item, isRead: true } : item)); }
    setNotificationsOpen(false); router.push(notificationHref(note.type));
  };

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    router.push(`/${currentLocale}/search?q=${encodeURIComponent(query)}`);
  };

  const navLinks = [
    { name: currentLocale === 'vi' ? 'Trang chủ' : 'Home', href: `/${currentLocale}`, icon: Home, active: pathname === `/${currentLocale}` },
    { name: currentLocale === 'vi' ? 'Mua bán' : 'Trade', href: `/${currentLocale}/search`, icon: ShoppingBag, active: pathname.includes('/search') },
    { name: currentLocale === 'vi' ? 'Diễn Đàn' : 'Forum', href: '#', icon: MessagesSquare, active: false },
    { name: currentLocale === 'vi' ? 'Hỗ trợ' : 'Support', href: '#', icon: HeadphonesIcon, active: false, action: 'support-chat' },
  ];

  return (
    <header className="sticky top-0 z-50 w-full border-b border-white/5 bg-background/95 backdrop-blur">
      <div className="container mx-auto flex h-16 items-center justify-between px-4 gap-4">

        {/* Left: Logo & Search */}
        <div className="flex items-center gap-6 flex-1 max-w-2xl">
          <Link href={`/${currentLocale}`} className="flex items-center gap-2 font-black text-2xl tracking-tighter shrink-0">
            <span className="text-foreground">{siteName}</span>
          </Link>

          <form onSubmit={handleSearch} className="flex-1 relative hidden md:block">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-500" />
            <Input
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder={currentLocale === 'vi' ? 'Tìm phần mềm, thẻ quà tặng, mã, dịch vụ...' : 'Search for software, gift cards, codes, services...'}
              className="pl-9 bg-white/5 border-white/10 text-sm text-gray-300 placeholder:text-gray-500 focus:border-primary/50 focus:bg-white/10 rounded-full h-10 w-full"
            />
          </form>
        </div>

        {/* Center: Navigation Links */}
        <nav className="hidden lg:flex items-center gap-6">
          {navLinks.map((link) => {
            const Icon = link.icon;
            if (link.action === 'support-chat') return <button key={link.name} onClick={() => { if (token) window.dispatchEvent(new Event('open-support-chat')); else router.push(`/${currentLocale}/auth/login`); }} className="flex items-center gap-1.5 text-sm font-medium text-gray-400 transition-colors hover:text-white"><Icon className="w-4 h-4" />{link.name}</button>;
            return (
              <Link
                key={link.name}
                href={link.href}
                className={`flex items-center gap-1.5 text-sm font-medium transition-colors ${
                  link.active ? 'text-[var(--brand-primary)]' : link.href === '#' ? 'text-gray-500 cursor-not-allowed opacity-50 pointer-events-none' : 'text-gray-400 hover:text-white'
                }`}
              >
                <Icon className="w-4 h-4" />
                {link.name}
              </Link>
            );
          })}
        </nav>

        {/* Right: Actions */}
        <div className="flex items-center gap-3 shrink-0">
          <Button variant="ghost" size="icon" className="text-gray-400 hover:text-white rounded-full bg-white/5 h-9 w-9 hidden sm:flex">
            <Bookmark className="w-4 h-4" />
          </Button>

          <div className="relative hidden sm:block">
            <Button onClick={() => void toggleNotifications()} variant="ghost" size="icon" className="text-gray-400 hover:text-white rounded-full bg-white/5 h-9 w-9 relative">
              <Bell className="w-4 h-4" />
              {token && unreadNotifications > 0 && <span className="absolute -right-1 -top-1 flex min-h-4 min-w-4 items-center justify-center rounded-full border border-background bg-red-500 px-1 text-[9px] font-bold text-white">{unreadNotifications > 9 ? '9+' : unreadNotifications}</span>}
            </Button>
            {notificationsOpen && <div className="absolute right-0 top-12 z-[70] w-[360px] overflow-hidden rounded-2xl border border-white/10 bg-[#151619] shadow-2xl">
              <div className="flex items-start justify-between px-4 pb-2 pt-4"><div><h3 className="text-base font-black text-white">Thông báo</h3><p className="mt-0.5 text-xs font-bold text-red-400">{unreadNotifications} chưa đọc</p></div><button onClick={() => void readNotifications()} disabled={!unreadNotifications} className="flex items-center gap-1 text-xs font-semibold text-gray-400 hover:text-white disabled:opacity-40"><CheckCircle2 className="h-4 w-4" />Đánh dấu tất cả đã đọc</button></div>
              <div className="flex gap-2 px-4 pb-3">{([{ key: 'ALL', label: 'Tất cả' }, { key: 'TRANSACTION', label: 'Giao dịch' }, { key: 'SYSTEM', label: 'Hệ thống' }, { key: 'PROMOTION', label: 'Khuyến mãi' }] as const).map((item) => <button key={item.key} onClick={() => setNotificationFilter(item.key)} className={`rounded-full border px-3 py-1.5 text-xs font-bold ${notificationFilter === item.key ? 'border-red-500/40 bg-red-500/10 text-red-300' : 'border-white/15 text-gray-400 hover:text-white'}`}>{item.label}</button>)}</div>
              <div className="max-h-[340px] overflow-y-auto border-t border-white/10 p-2">{notifications.filter((note) => notificationFilter === 'ALL' || category(note.type) === notificationFilter).length ? notifications.filter((note) => notificationFilter === 'ALL' || category(note.type) === notificationFilter).map((note) => { const Icon = category(note.type) === 'TRANSACTION' ? CreditCard : category(note.type) === 'PROMOTION' ? Gift : Info; return <button key={note.id} onClick={() => void openNotification(note)} className={`flex w-full gap-3 rounded-xl p-3 text-left transition-colors hover:bg-white/5 ${note.isRead ? 'opacity-60' : 'bg-red-500/[0.04]'}`}><span className={`mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-full ${note.isRead ? 'bg-white/5 text-gray-500' : 'bg-red-500/10 text-red-300'}`}><Icon className="h-4 w-4" /></span><span className="min-w-0 flex-1"><span className="flex items-center gap-2"><b className="truncate text-sm text-white">{note.title}</b>{!note.isRead && <i className="h-2 w-2 shrink-0 rounded-full bg-red-500" />}</span><span className="mt-1 line-clamp-2 block text-xs text-gray-400">{note.message}</span><span className="mt-1 block text-[10px] text-gray-600">{new Date(note.createdAt).toLocaleString('vi-VN')}</span></span></button>; }) : <div className="m-1 rounded-xl border border-dashed border-white/15 px-4 py-8 text-center text-sm font-medium text-gray-500">Chưa có thông báo nào.</div>}</div>
              <div className="flex items-center justify-between border-t border-white/10 px-4 py-3"><Link href={`/${currentLocale}/profile/edit#section-notifications`} onClick={() => setNotificationsOpen(false)} className="flex items-center gap-2 text-sm text-gray-400 hover:text-white"><Settings className="h-4 w-4" />Cài đặt thông báo</Link><Link href={`/${currentLocale}/profile`} onClick={() => setNotificationsOpen(false)} className="flex items-center gap-1 text-sm font-bold text-red-400 hover:text-red-300">Xem tất cả <ChevronRight className="h-4 w-4" /></Link></div>
            </div>}
          </div>

          {/* User Section */}
          <div className="flex items-center pl-2 border-l border-white/10 ml-2">
            {token ? (
              <UserDropdown />
            ) : (
              <div className="flex items-center gap-2">
                <Link href={`/${currentLocale}/auth/login`}>
                  <Button variant="ghost" size="sm" className="text-gray-300 hover:text-white">
                    {t('login')}
                  </Button>
                </Link>
                <Link href={`/${currentLocale}/auth/register`}>
                  <Button size="sm" className="text-white rounded-full px-5" style={{ backgroundColor: primaryColor }}>
                    {t('register')}
                  </Button>
                </Link>
              </div>
            )}
          </div>
        </div>
      </div>
    </header>
  );
}
