'use client';

import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import {
  Menu,
  Search,
  Copy,
  Check,
  Phone,
  User,
  Users,
  LogOut,
  X,
  ChevronRight,
  ChevronDown,
  Sun,
  Moon,
  Coins,
  Shield,
  Layers,
  Sparkles,
  Bell,
  CheckCircle2,
  KeyRound,
  ShieldCheck,
  Laptop,
} from 'lucide-react';

interface HeaderProps {
  user: any;
  wallet?: any;
  onToggleSidebar?: () => void;
}

export default function NINAuthHeader({ user, wallet, onToggleSidebar }: HeaderProps) {
  const router = useRouter();
  const [accountMenuOpen, setAccountMenuOpen] = useState(false);
  const [notificationsOpen, setNotificationsOpen] = useState(false);
  const [notifications, setNotifications] = useState<any[]>([]);
  const [unreadCount, setUnreadCount] = useState(2);
  const [isProductionMode, setIsProductionMode] = useState(false);
  const [theme, setTheme] = useState<'light' | 'dark' | 'system'>('light');
  const [copiedId, setCopiedId] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);

  const fullName = user?.name || 'SmartAuth User';
  const companyName = user?.orgName || user?.company || fullName;
  const email = user?.email || 'user@smartauth.ng';
  const userCode = user?.userCode || 'USR-2026-000001';
  const phone = user?.phone || '0802 000 0000';
  const unitsBalance = wallet?.unitsBalance ?? (user?.wallet?.unitsBalance ?? 1000);
  const accountType = user?.accountType === 'ORGANIZATION' ? 'ORGANIZATION' : 'INDIVIDUAL';
  const role = user?.role || 'STANDARD_USER';

  // Current hour greeting
  const hour = new Date().getHours();
  const greeting = hour < 12 ? 'Good morning' : hour < 18 ? 'Good afternoon' : 'Good evening';

  useEffect(() => {
    fetch('/api/v1/notifications')
      .then((res) => res.json())
      .then((data) => {
        if (data.success) {
          setNotifications(data.data.notifications || []);
          setUnreadCount(data.data.unreadCount || 0);
        }
      })
      .catch(() => {});
  }, []);

  const handleCopyId = () => {
    navigator.clipboard.writeText(userCode);
    setCopiedId(true);
    setTimeout(() => setCopiedId(false), 2000);
  };

  const handleThemeChange = (newTheme: 'light' | 'dark' | 'system') => {
    setTheme(newTheme);
    if (newTheme === 'dark') {
      document.documentElement.classList.add('dark');
    } else if (newTheme === 'light') {
      document.documentElement.classList.remove('dark');
    } else {
      if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
        document.documentElement.classList.add('dark');
      } else {
        document.documentElement.classList.remove('dark');
      }
    }
  };

  const handleLogout = async () => {
    await fetch('/api/v1/auth/logout', { method: 'POST' });
    router.push('/login');
  };

  return (
    <header className="h-16 border-b border-slate-200/90 bg-white/95 backdrop-blur-md px-4 sm:px-6 flex items-center justify-between sticky top-0 z-30 shadow-[0_1px_2px_rgba(0,0,0,0.03)] font-sans">
      {/* Left: Sidebar toggle & Greeting */}
      <div className="flex items-center gap-3 min-w-0">
        <button
          onClick={onToggleSidebar}
          className="p-2 text-slate-500 hover:text-slate-900 rounded-xl hover:bg-slate-100 transition-colors"
          title="Toggle Navigation"
        >
          <Menu className="w-5 h-5" />
        </button>

        <div className="flex items-center gap-2 truncate">
          <h2 className="text-sm sm:text-base font-bold text-slate-900 truncate">
            {greeting}, <span className="text-emerald-700">{fullName}</span>
          </h2>
          <span className="hidden md:inline-flex px-2 py-0.5 rounded-md text-[10.5px] font-mono font-bold bg-emerald-50 text-emerald-800 border border-emerald-200">
            {userCode}
          </span>
        </div>
      </div>

      {/* Right Area: Units + Notification + Profile */}
      <div className="flex items-center gap-2.5 sm:gap-3">
        {/* Available Units Badge */}
        <Link
          href="/dashboard/transactions"
          className="flex items-center gap-1.5 px-3 py-1.5 bg-amber-50/80 border border-amber-200/80 rounded-full text-xs font-bold text-amber-900 hover:bg-amber-100 transition-colors shadow-sm"
          title="Available Units Balance"
        >
          <Coins className="w-3.5 h-3.5 text-amber-600" />
          <span>{Number(unitsBalance).toLocaleString()} <span className="text-[10px] text-amber-700 font-mono">Units</span></span>
        </Link>

        {/* Environment Sandbox Pill */}
        <div className="hidden lg:flex items-center gap-1.5 bg-emerald-50 border border-emerald-200 rounded-full px-2.5 py-1 text-[11px] font-bold text-emerald-800 shadow-sm">
          <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span>
          <span>SANDBOX</span>
        </div>

        {/* Notification Bell */}
        <div className="relative">
          <button
            onClick={() => {
              setNotificationsOpen(!notificationsOpen);
              setAccountMenuOpen(false);
            }}
            className="w-9 h-9 rounded-full bg-slate-50 hover:bg-slate-100 border border-slate-200/80 flex items-center justify-center text-slate-600 hover:text-slate-900 transition-colors relative"
            title="Notifications"
          >
            <Bell className="w-4 h-4" />
            {unreadCount > 0 && (
              <span className="absolute top-1 right-1 w-2 h-2 rounded-full bg-emerald-500 ring-2 ring-white"></span>
            )}
          </button>

          {/* Notifications Popover */}
          {notificationsOpen && (
            <div className="absolute right-0 mt-3 w-80 sm:w-96 bg-white rounded-2xl shadow-2xl border border-slate-200 p-4 space-y-3 animate-in fade-in zoom-in-95 duration-150 z-50">
              <div className="flex items-center justify-between border-b border-slate-100 pb-2.5">
                <div className="flex items-center gap-2">
                  <Bell className="w-4 h-4 text-emerald-600" />
                  <span className="text-xs font-bold text-slate-900">Notifications</span>
                </div>
                <span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700">
                  {unreadCount} Unread
                </span>
              </div>

              <div className="space-y-2 max-h-64 overflow-y-auto">
                {notifications.map((n) => (
                  <div
                    key={n.id}
                    className={`p-3 rounded-xl border text-xs space-y-1 transition-all ${
                      n.read
                        ? 'bg-slate-50 border-slate-100 text-slate-600'
                        : 'bg-emerald-50/50 border-emerald-200/80 text-slate-900 shadow-sm'
                    }`}
                  >
                    <div className="flex items-center justify-between font-bold text-[11.5px]">
                      <span>{n.title}</span>
                      <span className="text-[10px] text-slate-400 font-mono">{n.time}</span>
                    </div>
                    <p className="text-[11px] text-slate-600 leading-relaxed">{n.message}</p>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Top-Right Account Profile Trigger */}
        <div className="relative">
          <button
            onClick={() => {
              setAccountMenuOpen(!accountMenuOpen);
              setNotificationsOpen(false);
            }}
            className="flex items-center gap-2 p-1 sm:px-2.5 sm:py-1 rounded-full bg-slate-50 hover:bg-slate-100 border border-slate-200/90 transition-all text-slate-800"
          >
            <div className="w-7 h-7 rounded-full bg-emerald-700 text-white font-bold text-xs flex items-center justify-center shadow-sm">
              {fullName.charAt(0).toUpperCase()}
            </div>
            <span className="hidden sm:inline-block text-xs font-bold max-w-[100px] truncate">
              {fullName.split(' ')[0]}
            </span>
            <ChevronDown className="w-3.5 h-3.5 text-slate-400" />
          </button>

          {/* Account Profile Dropdown Menu */}
          {accountMenuOpen && (
            <div className="absolute right-0 mt-3 w-80 sm:w-88 bg-white rounded-2xl shadow-2xl border border-slate-200 p-5 space-y-4 animate-in fade-in zoom-in-95 duration-150 z-50">
              {/* Header Info */}
              <div className="flex items-center justify-between border-b border-slate-100 pb-3">
                <span className="text-[10.5px] font-mono font-bold text-slate-400 tracking-wider uppercase">
                  SMARTAUTH PROFILE
                </span>
                <button
                  onClick={() => setAccountMenuOpen(false)}
                  className="text-slate-400 hover:text-slate-600 p-0.5"
                >
                  <X className="w-4 h-4" />
                </button>
              </div>

              {/* User Identity Info */}
              <div className="flex items-center gap-3">
                <div className="w-11 h-11 rounded-full bg-gradient-to-tr from-emerald-600 to-teal-500 text-white font-extrabold text-base flex items-center justify-center shrink-0 shadow-sm">
                  {fullName.charAt(0).toUpperCase()}
                </div>
                <div className="min-w-0">
                  <h3 className="text-sm font-bold text-slate-900 truncate">
                    {fullName}
                  </h3>
                  <p className="text-xs text-slate-500 truncate font-mono">
                    {email}
                  </p>
                </div>
              </div>

              {/* Unique User ID with copy button */}
              <div className="flex items-center justify-between bg-slate-50 px-3.5 py-2 rounded-xl border border-slate-200/90 text-xs">
                <div className="flex items-center gap-2 text-slate-700 font-mono">
                  <span className="text-slate-400 text-xs font-sans">User ID:</span>
                  <span className="font-bold text-emerald-700">{userCode}</span>
                </div>
                <button
                  onClick={handleCopyId}
                  className="text-slate-400 hover:text-slate-700 p-1"
                  title="Copy User ID"
                >
                  {copiedId ? <Check className="w-4 h-4 text-emerald-600" /> : <Copy className="w-4 h-4" />}
                </button>
              </div>

              {/* Phone & Account Type */}
              <div className="flex items-center justify-between py-0.5 text-xs">
                <div className="flex items-center gap-1.5 text-slate-600 font-mono">
                  <Phone className="w-3.5 h-3.5 text-slate-400" />
                  <span>{phone}</span>
                </div>
                <span className="px-2 py-0.5 rounded text-[10px] font-bold text-slate-700 bg-slate-100 uppercase tracking-wide">
                  {accountType}
                </span>
              </div>

              {/* Theme switcher: Light / Dark / System */}
              <div className="flex items-center justify-between py-1 border-t border-slate-100 pt-3">
                <span className="text-xs font-semibold text-slate-700">Theme</span>
                <div className="flex bg-slate-100 rounded-xl p-0.5 border border-slate-200 text-xs">
                  <button
                    onClick={() => handleThemeChange('light')}
                    className={`px-2.5 py-1 rounded-lg text-[11px] font-bold transition-all flex items-center gap-1 ${
                      theme === 'light'
                        ? 'bg-white text-emerald-700 shadow-sm'
                        : 'text-slate-500 hover:text-slate-900'
                    }`}
                  >
                    <Sun className="w-3 h-3" />
                    <span>Light</span>
                  </button>
                  <button
                    onClick={() => handleThemeChange('dark')}
                    className={`px-2.5 py-1 rounded-lg text-[11px] font-bold transition-all flex items-center gap-1 ${
                      theme === 'dark'
                        ? 'bg-slate-900 text-white shadow-sm'
                        : 'text-slate-500 hover:text-slate-900'
                    }`}
                  >
                    <Moon className="w-3 h-3" />
                    <span>Dark</span>
                  </button>
                  <button
                    onClick={() => handleThemeChange('system')}
                    className={`px-2.5 py-1 rounded-lg text-[11px] font-bold transition-all flex items-center gap-1 ${
                      theme === 'system'
                        ? 'bg-white text-emerald-700 shadow-sm'
                        : 'text-slate-500 hover:text-slate-900'
                    }`}
                  >
                    <Laptop className="w-3 h-3" />
                    <span>Sys</span>
                  </button>
                </div>
              </div>

              {/* Navigation links */}
              <div className="space-y-1 border-t border-slate-100 pt-2">
                <Link
                  href="/dashboard/profile"
                  onClick={() => setAccountMenuOpen(false)}
                  className="w-full flex items-center justify-between px-2.5 py-2 rounded-xl text-xs font-semibold text-slate-700 hover:bg-slate-50 hover:text-slate-900 transition-colors"
                >
                  <div className="flex items-center gap-2.5">
                    <User className="w-4 h-4 text-emerald-600" />
                    <span>My Profile</span>
                  </div>
                  <ChevronRight className="w-4 h-4 text-slate-400" />
                </Link>

                <Link
                  href="/dashboard/settings"
                  onClick={() => setAccountMenuOpen(false)}
                  className="w-full flex items-center justify-between px-2.5 py-2 rounded-xl text-xs font-semibold text-slate-700 hover:bg-slate-50 hover:text-slate-900 transition-colors"
                >
                  <div className="flex items-center gap-2.5">
                    <KeyRound className="w-4 h-4 text-slate-400" />
                    <span>Account & Password</span>
                  </div>
                  <ChevronRight className="w-4 h-4 text-slate-400" />
                </Link>

                {role === 'API_USER' && (
                  <Link
                    href="/dashboard/team"
                    onClick={() => setAccountMenuOpen(false)}
                    className="w-full flex items-center justify-between px-2.5 py-2 rounded-xl text-xs font-semibold text-slate-700 hover:bg-slate-50 hover:text-slate-900 transition-colors"
                  >
                    <div className="flex items-center gap-2.5">
                      <Users className="w-4 h-4 text-slate-400" />
                      <span>Organization Members</span>
                    </div>
                    <ChevronRight className="w-4 h-4 text-slate-400" />
                  </Link>
                )}
              </div>

              {/* Sign out */}
              <div className="border-t border-slate-100 pt-2">
                <button
                  onClick={handleLogout}
                  className="w-full flex items-center gap-2.5 px-2.5 py-2 text-xs font-bold text-rose-600 hover:bg-rose-50 rounded-xl transition-colors"
                >
                  <LogOut className="w-4 h-4" />
                  <span>Sign out</span>
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </header>
  );
}
