'use client';

import Link from 'next/link';
import { useState, useEffect, useRef } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { useAuthStore } from '@/lib/store';
import { useTranslation } from '@/lib/i18n';
import { notificationApi, Notification } from '@/lib/api';
import LanguageSelector from './LanguageSelector';

// Menu groups for sidebar
export const MENU_GROUPS = {
  quote: {
    label: { ko: '견적요청', en: 'Quote', mn: 'Үнийн санал', ru: 'Запрос' },
    basePath: '/vehicle-request',
    items: [
      { path: '/vehicle-request', label: { ko: '차량요청하기', en: 'Request Vehicle', mn: 'Машин захиалах', ru: 'Запрос авто' } },
      { path: '/my-request', label: { ko: '내요청', en: 'My Requests', mn: 'Миний хүсэлт', ru: 'Мои запросы' } },
      { path: '/my-shares', label: { ko: '내공유목록', en: 'My Shares', mn: 'Миний хуваалцсан', ru: 'Мои ссылки' } },
      { path: '/find-my-car', label: { ko: '내차찾기', en: 'Find My Car', mn: 'Машинаа олох', ru: 'Найти мою машину' } },
    ],
  },
  billing: {
    label: { ko: '비용', en: 'Billing', mn: 'Төлбөр', ru: 'Оплата' },
    basePath: '/cost',
    items: [
      { path: '/cost', label: { ko: '비용계산', en: 'Cost Calculator', mn: 'Зардал тооцоо', ru: 'Калькулятор' } },
      { path: '/cc', label: { ko: 'CC 충전', en: 'Buy CC', mn: 'CC худалдан авах', ru: 'Купить CC' } },
      { path: '/charge', label: { ko: 'USDC/계좌', en: 'USDC/Bank', mn: 'USDC/Банк', ru: 'USDC/Банк' } },
      { path: '/withdrawal', label: { ko: '출금', en: 'Withdraw', mn: 'Татах', ru: 'Вывод' } },
    ],
  },
  inquiry: {
    label: { ko: '문의', en: 'Inquiry', mn: 'Асуулт', ru: 'Запрос' },
    basePath: '/my-inquiries',
    items: [
      { path: '/inquiry', label: { ko: '문의하기', en: 'New Inquiry', mn: 'Асуулт илгээх', ru: 'Новый запрос' } },
      { path: '/my-inquiries', label: { ko: '내 문의목록', en: 'My Inquiries', mn: 'Миний асуултууд', ru: 'Мои запросы' } },
    ],
  },
};

// Helper to check if current path belongs to a menu group
export function getActiveMenuGroup(pathname: string): string | null {
  for (const [key, group] of Object.entries(MENU_GROUPS)) {
    if (group.items.some(item => pathname === item.path || pathname.startsWith(item.path + '/'))) {
      return key;
    }
  }
  return null;
}

export default function Header() {
  const { user, logout } = useAuthStore();
  const { t, language } = useTranslation();
  const router = useRouter();
  const pathname = usePathname();

  // Notification state
  const [unreadCount, setUnreadCount] = useState(0);
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [showNotifications, setShowNotifications] = useState(false);
  const [loadingNotifications, setLoadingNotifications] = useState(false);
  const notificationRef = useRef<HTMLDivElement>(null);
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);

  const activeGroup = getActiveMenuGroup(pathname);

  // Fetch unread count periodically
  useEffect(() => {
    if (!user) return;

    const fetchUnreadCount = async () => {
      try {
        const { unread_count } = await notificationApi.getUnreadCount();
        setUnreadCount(unread_count);
      } catch (error) {
        console.error('Failed to fetch unread count:', error);
      }
    };

    fetchUnreadCount();
    const interval = setInterval(fetchUnreadCount, 30000);

    return () => clearInterval(interval);
  }, [user]);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (notificationRef.current && !notificationRef.current.contains(event.target as Node)) {
        setShowNotifications(false);
      }
    };

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

  // Fetch notifications when dropdown opens
  const handleNotificationClick = async () => {
    if (!showNotifications) {
      setLoadingNotifications(true);
      try {
        const response = await notificationApi.getNotifications(1, 10);
        setNotifications(response.notifications);
        setUnreadCount(response.unread_count);
      } catch (error) {
        console.error('Failed to fetch notifications:', error);
      } finally {
        setLoadingNotifications(false);
      }
    }
    setShowNotifications(!showNotifications);
  };

  // Mark notification as read and navigate
  const handleNotificationItemClick = async (notification: Notification) => {
    if (!notification.is_read) {
      try {
        await notificationApi.markAsRead([notification.id]);
        setUnreadCount(prev => Math.max(0, prev - 1));
        setNotifications(prev =>
          prev.map(n => n.id === notification.id ? { ...n, is_read: true } : n)
        );
      } catch (error) {
        console.error('Failed to mark as read:', error);
      }
    }

    setShowNotifications(false);
    if (notification.link) {
      router.push(notification.link);
    }
  };

  // Mark all as read
  const handleMarkAllRead = async () => {
    try {
      await notificationApi.markAllAsRead();
      setUnreadCount(0);
      setNotifications(prev => prev.map(n => ({ ...n, is_read: true })));
    } catch (error) {
      console.error('Failed to mark all as read:', error);
    }
  };

  // Format time ago
  const formatTimeAgo = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMins / 60);
    const diffDays = Math.floor(diffHours / 24);

    if (diffMins < 1) return '방금 전';
    if (diffMins < 60) return `${diffMins}분 전`;
    if (diffHours < 24) return `${diffHours}시간 전`;
    if (diffDays < 7) return `${diffDays}일 전`;
    return date.toLocaleDateString();
  };

  // Get notification icon based on type
  const getNotificationIcon = (type: string) => {
    switch (type) {
      case 'vehicle_recommended': return '🚗';
      case 'shipping_update': return '🚚';
      case 'withdrawal_processed': return '💰';
      case 'referral_reward': return '🎁';
      case 'dealer_approved': return '✅';
      case 'dealer_rejected': return '❌';
      case 'share_purchased': return '🎉';
      case 'system': return '📢';
      default: return '🔔';
    }
  };

  // Get label based on language
  const getLabel = (labelObj: { ko: string; en: string; mn: string; ru: string }) => {
    return labelObj[language as keyof typeof labelObj] || labelObj.en;
  };

  // Navigation menu items
  const navItems = [
    { href: '/about', label: { ko: '소개', en: 'About', mn: 'Тухай', ru: 'О нас' } },
    { href: MENU_GROUPS.quote.basePath, label: MENU_GROUPS.quote.label, group: 'quote' },
    { href: MENU_GROUPS.billing.basePath, label: MENU_GROUPS.billing.label, group: 'billing' },
    { href: '/exchange-rate', label: { ko: '환율', en: 'Exchange', mn: 'Ханш', ru: 'Курс' } },
    { href: MENU_GROUPS.inquiry.basePath, label: MENU_GROUPS.inquiry.label, group: 'inquiry' },
    { href: '/contact', label: { ko: '연락처', en: 'Contact Us', mn: 'Холбоо барих', ru: 'Контакты' } },
  ];

  return (
    <header className="bg-primary-700 text-white shadow-lg">
      <div className="container mx-auto px-4">
        <div className="flex items-center justify-between h-16">
          {/* Logo */}
          <Link href="/" className="text-2xl font-bold">
            AutonetSellCar
          </Link>

          {/* Desktop Navigation */}
          <nav className="hidden md:flex space-x-10">
            {navItems.map((item) => {
              const isActive = item.group ? activeGroup === item.group : pathname === item.href;
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  className={`hover:text-primary-200 transition ${isActive ? 'text-white font-semibold border-b-2 border-white pb-1' : ''}`}
                >
                  {getLabel(item.label)}
                </Link>
              );
            })}
          </nav>

          {/* Right side: Notifications + Language + Auth */}
          <div className="flex items-center space-x-4">
            {/* Notification Bell */}
            {user && (
              <div className="relative" ref={notificationRef}>
                <button
                  onClick={handleNotificationClick}
                  className="relative p-2 hover:bg-primary-600 rounded-full transition"
                  title={t.notifications || '알림'}
                >
                  <svg
                    className="w-6 h-6"
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth={2}
                      d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9"
                    />
                  </svg>
                  {unreadCount > 0 && (
                    <span className="absolute -top-1 -right-1 bg-red-500 text-white text-xs rounded-full w-5 h-5 flex items-center justify-center">
                      {unreadCount > 9 ? '9+' : unreadCount}
                    </span>
                  )}
                </button>

                {/* Notification Dropdown */}
                {showNotifications && (
                  <div className="absolute right-0 mt-2 w-80 bg-white rounded-lg shadow-xl z-50 text-gray-800 max-h-96 overflow-hidden">
                    {/* Header */}
                    <div className="flex items-center justify-between px-4 py-3 border-b bg-gray-50">
                      <span className="font-semibold">{t.notifications || '알림'}</span>
                      {unreadCount > 0 && (
                        <button
                          onClick={handleMarkAllRead}
                          className="text-sm text-primary-600 hover:text-primary-700"
                        >
                          {t.markAllRead || '모두 읽음'}
                        </button>
                      )}
                    </div>

                    {/* Notification List */}
                    <div className="max-h-72 overflow-y-auto">
                      {loadingNotifications ? (
                        <div className="p-4 text-center text-gray-500">
                          <div className="animate-spin w-6 h-6 border-2 border-primary-600 border-t-transparent rounded-full mx-auto"></div>
                        </div>
                      ) : notifications.length === 0 ? (
                        <div className="p-8 text-center text-gray-500">
                          {t.noNotifications || '알림이 없습니다'}
                        </div>
                      ) : (
                        notifications.map((notification) => (
                          <div
                            key={notification.id}
                            onClick={() => handleNotificationItemClick(notification)}
                            className={`px-4 py-3 border-b hover:bg-gray-50 cursor-pointer transition ${
                              !notification.is_read ? 'bg-blue-50' : ''
                            }`}
                          >
                            <div className="flex items-start gap-3">
                              <span className="text-xl">
                                {getNotificationIcon(notification.notification_type)}
                              </span>
                              <div className="flex-1 min-w-0">
                                <p className={`text-sm ${!notification.is_read ? 'font-semibold' : ''}`}>
                                  {notification.title}
                                </p>
                                <p className="text-xs text-gray-600 mt-1 line-clamp-2">
                                  {notification.message}
                                </p>
                                <p className="text-xs text-gray-400 mt-1">
                                  {formatTimeAgo(notification.created_at)}
                                </p>
                              </div>
                              {!notification.is_read && (
                                <span className="w-2 h-2 bg-blue-500 rounded-full flex-shrink-0 mt-2"></span>
                              )}
                            </div>
                          </div>
                        ))
                      )}
                    </div>

                    {/* Footer */}
                    {notifications.length > 0 && (
                      <div className="px-4 py-2 border-t bg-gray-50 text-center">
                        <Link
                          href="/notifications"
                          className="text-sm text-primary-600 hover:text-primary-700"
                          onClick={() => setShowNotifications(false)}
                        >
                          {t.viewAllNotifications || '모든 알림 보기'}
                        </Link>
                      </div>
                    )}
                  </div>
                )}
              </div>
            )}

            {/* Language Selector */}
            <LanguageSelector />

            {/* Auth */}
            {user ? (
              <>
                <Link
                  href="/profile"
                  className="text-sm hidden sm:inline hover:text-primary-200 transition cursor-pointer"
                >
                  Hello, {user.name || user.email}
                </Link>
                <button
                  onClick={logout}
                  className="bg-primary-600 hover:bg-primary-500 px-4 py-2 rounded transition"
                >
                  {t.logout}
                </button>
              </>
            ) : (
              <>
                <Link
                  href="/login"
                  className="hover:text-primary-200 transition hidden sm:inline"
                >
                  {t.login}
                </Link>
                <Link
                  href="/register"
                  className="bg-white text-primary-700 hover:bg-primary-100 px-4 py-2 rounded transition"
                >
                  {t.register}
                </Link>
              </>
            )}

            {/* Mobile menu button */}
            <button
              className="md:hidden p-2 hover:bg-primary-600 rounded"
              onClick={() => setMobileMenuOpen(!mobileMenuOpen)}
            >
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                {mobileMenuOpen ? (
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                ) : (
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                )}
              </svg>
            </button>
          </div>
        </div>

        {/* Mobile Navigation */}
        {mobileMenuOpen && (
          <nav className="md:hidden py-4 border-t border-primary-600">
            {navItems.map((item) => {
              const isActive = item.group ? activeGroup === item.group : pathname === item.href;
              return (
                <Link
                  key={item.href}
                  href={item.href}
                  className={`block py-2 hover:text-primary-200 transition ${isActive ? 'text-white font-semibold' : ''}`}
                  onClick={() => setMobileMenuOpen(false)}
                >
                  {getLabel(item.label)}
                </Link>
              );
            })}
          </nav>
        )}
      </div>
    </header>
  );
}
