'use client';

import { useEffect, useRef, useState } from 'react';
import Link from 'next/link';
import { Bell, Search, ChevronDown, Check, Plus, CheckCheck } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { useRealtime } from '@/lib/realtime';
import { useAuth } from '@/lib/auth-context';
import { adminApiFetch } from '@/lib/api';

type SearchResult = { type: string; label: string; href: string };

export default function Header() {
  const { user, logout, accessToken, appSecretProof } = useAuth();
  const router = useRouter();
  const { counts, notifications, markAllRead, markRead, refreshNotifications } = useRealtime();
  const initials = user?.name?.split(' ').map((n) => n[0]).slice(0, 2).join('') || '—';

  // ── Search ──────────────────────────────────────────────────────────
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<SearchResult[]>([]);
  const [showResults, setShowResults] = useState(false);
  const searchBoxRef = useRef<HTMLDivElement>(null);
  const searchInputRef = useRef<HTMLInputElement>(null);

  // Cmd/Ctrl+K — jumps straight to the search box from anywhere in the
  // admin, same shortcut people expect from a command palette, without
  // needing a whole separate overlay component: this search box already
  // covers products/clients/quotes/orders/tickets/invoices.
  useEffect(() => {
    function onKeyDown(e: KeyboardEvent) {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
        e.preventDefault();
        searchInputRef.current?.focus();
        setShowResults(true);
      }
      if (e.key === 'Escape') setShowResults(false);
    }
    document.addEventListener('keydown', onKeyDown);
    return () => document.removeEventListener('keydown', onKeyDown);
  }, []);

  useEffect(() => {
    if (!accessToken || !appSecretProof || query.trim().length < 2) { setResults([]); return; }
    const t = setTimeout(() => {
      adminApiFetch(`/admin/search?q=${encodeURIComponent(query)}`, accessToken, appSecretProof)
        .then((d) => setResults(d.results || []))
        .catch(() => setResults([]));
    }, 250); // debounce
    return () => clearTimeout(t);
  }, [query, accessToken, appSecretProof]);

  useEffect(() => {
    function onClickOutside(e: MouseEvent) {
      if (searchBoxRef.current && !searchBoxRef.current.contains(e.target as Node)) setShowResults(false);
    }
    document.addEventListener('mousedown', onClickOutside);
    return () => document.removeEventListener('mousedown', onClickOutside);
  }, []);

  // ── Notifications (live: the bell and the menu badges update over the WebSocket) ──
  const [notifOpen, setNotifOpen] = useState(false);
  const notifCount = counts.total;
  const ago = (iso: string) => {
    const m = Math.round((Date.now() - new Date(iso).getTime()) / 60000);
    return m < 1 ? 'just now' : m < 60 ? `${m}m ago` : m < 1440 ? `${Math.round(m / 60)}h ago` : `${Math.round(m / 1440)}d ago`;
  };

  // ── Business switcher ───────────────────────────────────────────────
  const [switcherOpen, setSwitcherOpen] = useState(false);

  return (
    <header className="h-[64px] bg-white border-b border-brand-border flex items-center justify-between px-4 sticky top-0 z-20">
      <div className="flex items-center gap-3">
        {/* Business switcher — LUSSAVARA is the only business in this
            system today; this is real UI, not a stub for a feature that
            doesn't exist yet, but there's genuinely nothing to switch TO
            until a second business is onboarded. */}
        <div className="relative hidden md:block">
          <button onClick={() => setSwitcherOpen((v) => !v)} className="flex items-center gap-1.5 text-xs font-semibold px-2 py-1.5 rounded-lg transition-colors hover:bg-brand-bg">
            LUSSAVARA Company Limited <ChevronDown size={14} className="text-gray-400" />
          </button>
          {switcherOpen && (
            <div className="absolute left-0 mt-1 w-64 bg-white border border-brand-border rounded-xl shadow-lg py-1 z-30 animate-scaleIn">
              <div className="px-3 py-2 flex items-center justify-between text-xs">
                <span className="font-medium">LUSSAVARA Company Limited</span>
                <Check size={14} className="text-brand-red" />
              </div>
              <div className="border-t border-brand-border" />
              <button disabled className="w-full text-left px-3 py-2 text-xs text-gray-300 flex items-center gap-1.5 cursor-not-allowed">
                <Plus size={12} /> Add Business (coming soon)
              </button>
            </div>
          )}
        </div>

        <div ref={searchBoxRef} className="relative hidden md:block">
          <Search className="absolute left-3 top-2.5 text-gray-400" size={16} />
          <input
            ref={searchInputRef}
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            onFocus={() => setShowResults(true)}
            placeholder="Search product, quote, client, ticket, invoice…"
            className="pl-9 pr-12 py-2 w-[320px] bg-brand-bg border border-brand-border rounded-full text-sm transition-colors duration-150 focus:outline-none focus:border-brand-red"
          />
          <kbd className="absolute right-3 top-2 text-[10px] text-gray-400 border border-brand-border rounded px-1.5 py-0.5 bg-white pointer-events-none">&#8984;K</kbd>
          {showResults && query.trim().length >= 2 && (
            <div className="absolute left-0 mt-1 w-full bg-white border border-brand-border rounded-xl shadow-lg py-1 z-30 max-h-72 overflow-y-auto animate-scaleIn">
              {results.length === 0 && <p className="px-3 py-2 text-xs text-gray-400">No matches.</p>}
              {results.map((r, i) => (
                <Link key={i} href={r.href} onClick={() => setShowResults(false)} className="block px-3 py-2 text-xs transition-colors hover:bg-brand-bg">
                  <span className="text-gray-400 mr-1">{r.type}</span>{r.label}
                </Link>
              ))}
            </div>
          )}
        </div>
      </div>

      <div className="flex items-center gap-3">
        <div className="relative">
          <button onClick={() => { setNotifOpen((v) => !v); refreshNotifications(); }} className="relative p-2 hover:bg-gray-100 rounded transition-colors duration-150">
            <Bell size={18} />
            {notifCount > 0 && (
              <span className="absolute -top-0.5 -right-0.5 bg-brand-red text-white text-[9px] rounded-full min-w-4 h-4 px-1 flex items-center justify-center">{notifCount > 99 ? '99+' : notifCount}</span>
            )}
          </button>
          {notifOpen && (
            <div className="absolute right-0 mt-1 w-80 bg-white border border-brand-border rounded-xl shadow-lg z-30 animate-scaleIn">
              <div className="px-3 py-2 flex items-center justify-between border-b border-brand-border">
                <p className="text-xs font-semibold">Notifications</p>
                {notifCount > 0 && (
                  <button onClick={markAllRead} className="text-[10px] text-gray-500 hover:text-brand-red flex items-center gap-1"><CheckCheck size={12} /> Mark all read</button>
                )}
              </div>
              <div className="max-h-80 overflow-y-auto py-1">
                {notifications.length === 0 && <p className="px-3 py-3 text-xs text-gray-400">Nothing yet.</p>}
                {notifications.map((n) => (
                  <button key={n.id} onClick={() => { setNotifOpen(false); if (!n.readAt) markRead(n.section, n.refId ?? undefined); if (n.href) router.push(n.href); }}
                    className={`w-full text-left px-3 py-2 transition-colors hover:bg-brand-bg flex gap-2 ${n.readAt ? '' : 'bg-red-50/50'}`}>
                    <span className={`mt-1.5 w-1.5 h-1.5 rounded-full shrink-0 ${n.readAt ? 'bg-transparent' : 'bg-brand-red'}`} />
                    <span className="min-w-0">
                      <span className="block text-xs font-medium truncate">{n.title}</span>
                      {n.body && <span className="block text-[11px] text-gray-500 truncate">{n.body}</span>}
                      <span className="block text-[10px] text-gray-400">{ago(n.createdAt)}</span>
                    </span>
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>
        <div className="flex items-center gap-2 pl-3 border-l border-brand-border">
          <div className="w-8 h-8 rounded-full bg-brand-red text-white flex items-center justify-center text-xs font-bold">{initials}</div>
          <div className="hidden md:block">
            <p className="text-xs font-semibold">{user?.name}</p>
            <p className="text-[10px] text-gray-500">{user?.role}</p>
          </div>
          <button onClick={logout} className="text-xs text-gray-500 hover:text-brand-red ml-2 transition-colors duration-150">Sign out</button>
        </div>
      </div>
    </header>
  );
}
