'use client';

import React, { useState } from 'react';
import { AdminRole } from '@/types';
import AppLogo from '@/components/common/AppLogo';

interface TopNavProps {
  searchQuery: string;
  onSearchChange: (query: string) => void;
  onSearchSubmit: (e: React.FormEvent) => void;
  adminUser: {
    id: string;
    name: string;
    email: string;
    role: AdminRole;
    avatar_url?: string | null;
  } | null;
  onRoleSwitch?: (role: AdminRole) => void;
  onLogout: () => void;
  onOpenMobileSidebar: () => void;
  unreadNotificationsCount?: number;
}

export default function SaasAdminTopNav({
  searchQuery,
  onSearchChange,
  onSearchSubmit,
  adminUser,
  onRoleSwitch,
  onLogout,
  onOpenMobileSidebar,
  unreadNotificationsCount = 0,
}: TopNavProps) {
  const [profileOpen, setProfileOpen] = useState(false);
  const [notifOpen, setNotifOpen] = useState(false);

  const roleBadge = (role: AdminRole) => {
    switch (role) {
      case 'super_admin':
        return 'bg-purple-100 text-purple-800 border-purple-200';
      case 'billing_admin':
        return 'bg-blue-100 text-blue-800 border-blue-200';
      case 'support_agent':
        return 'bg-amber-100 text-amber-800 border-amber-200';
      default:
        return 'bg-slate-100 text-slate-700 border-slate-200';
    }
  };

  return (
    <header className="h-16 bg-white border-b border-slate-200/90 px-4 sm:px-6 flex items-center justify-between gap-4 sticky top-0 z-30 shadow-2xs">
      {/* Left: Mobile Toggle & Global Search Bar */}
      <div className="flex items-center gap-3 flex-1 max-w-xl">
        <button
          onClick={onOpenMobileSidebar}
          className="lg:hidden p-2 rounded-xl text-slate-500 hover:text-slate-800 hover:bg-slate-100 cursor-pointer"
        >
          <i className="fa-solid fa-bars text-sm" />
        </button>

        <AppLogo size="sm" className="lg:hidden shrink-0" />

        <form onSubmit={onSearchSubmit} className="relative w-full">
          <i className="fa-solid fa-magnifying-glass text-slate-400 text-xs absolute left-3.5 top-1/2 -translate-y-1/2" />
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => onSearchChange(e.target.value)}
            placeholder="Search Shopify store name, domain, owner email, or shop ID..."
            className="w-full pl-9 pr-4 py-2 rounded-xl border border-slate-200 text-xs text-slate-800 placeholder:text-slate-400 bg-slate-50/70 focus:bg-white focus:outline-none focus:ring-2 focus:ring-theme/20 focus:border-theme transition-all"
          />
        </form>
      </div>

      {/* Right: Mode Toggle, Notifications & Profile */}
      <div className="flex items-center gap-2.5 sm:gap-4 shrink-0">
        {/* Real-time Status Badge */}
        <div className="hidden sm:flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-emerald-50 border border-emerald-200/70 text-[11px] font-semibold text-emerald-800">
          <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
          <span>Live Production Data</span>
        </div>

        {/* Notifications Dropdown */}
        <div className="relative">
          <button
            onClick={() => setNotifOpen(!notifOpen)}
            className="w-9 h-9 rounded-xl border border-slate-200/80 hover:bg-slate-50 text-slate-600 flex items-center justify-center relative cursor-pointer"
          >
            <i className="fa-regular fa-bell text-xs" />
            {unreadNotificationsCount > 0 && (
              <span className="absolute -top-1 -right-1 w-4 h-4 rounded-full bg-rose-500 text-white text-[9px] font-black flex items-center justify-center border-2 border-white">
                {unreadNotificationsCount}
              </span>
            )}
          </button>

          {notifOpen && (
            <div className="absolute right-0 mt-2 w-80 sm:w-96 rounded-2xl bg-white border border-slate-200 shadow-xl p-4 z-50 animate-in fade-in zoom-in-95">
              <div className="flex items-center justify-between pb-3 border-b border-slate-100">
                <span className="text-xs font-bold text-slate-900">Admin Activity Alerts</span>
                <span className="text-[10px] font-semibold text-theme hover:underline cursor-pointer">
                  Mark all as read
                </span>
              </div>
              <div className="py-2 space-y-2.5 max-h-72 overflow-y-auto">
                <div className="p-2.5 rounded-xl bg-emerald-50/60 border border-emerald-100/70 text-xs space-y-1">
                  <div className="flex items-center justify-between text-[10px] font-bold text-emerald-800">
                    <span className="flex items-center gap-1.5">
                      <i className="fa-solid fa-circle-plus text-emerald-600" />
                      <span>New Store Installed</span>
                    </span>
                    <span className="text-slate-400">12m ago</span>
                  </div>
                  <p className="text-[11px] text-slate-700">
                    <strong>Aurora Apparel &amp; Co.</strong> authorized OAuth and installed the app.
                  </p>
                </div>

                <div className="p-2.5 rounded-xl bg-blue-50/60 border border-blue-100/70 text-xs space-y-1">
                  <div className="flex items-center justify-between text-[10px] font-bold text-blue-800">
                    <span className="flex items-center gap-1.5">
                      <i className="fa-solid fa-arrow-up text-blue-600" />
                      <span>Subscription Upgrade</span>
                    </span>
                    <span className="text-slate-400">2h ago</span>
                  </div>
                  <p className="text-[11px] text-slate-700">
                    <strong>Tokyo Drift Harajuku</strong> upgraded to Accelerate Plan ($99.00/mo).
                  </p>
                </div>

                <div className="p-2.5 rounded-xl bg-amber-50/60 border border-amber-100/70 text-xs space-y-1">
                  <div className="flex items-center justify-between text-[10px] font-bold text-amber-800">
                    <span className="flex items-center gap-1.5">
                      <i className="fa-solid fa-triangle-exclamation text-amber-600" />
                      <span>Payment Past Due</span>
                    </span>
                    <span className="text-slate-400">1d ago</span>
                  </div>
                  <p className="text-[11px] text-slate-700">
                    <strong>Alpine Summit Outfitters</strong> billing charge of $13.00 is overdue.
                  </p>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Admin Profile & Role Dropdown */}
        <div className="relative">
          <button
            onClick={() => setProfileOpen(!profileOpen)}
            className="flex items-center gap-2 p-1.5 sm:px-3 sm:py-1.5 rounded-xl border border-slate-200/80 hover:bg-slate-50 cursor-pointer"
          >
            <div className="w-7 h-7 rounded-lg bg-slate-900 text-white text-xs font-bold flex items-center justify-center shrink-0">
              {adminUser?.name ? adminUser.name.charAt(0) : 'A'}
            </div>
            <div className="hidden sm:block text-left">
              <div className="text-xs font-bold text-slate-900 leading-tight truncate max-w-[120px]">
                {adminUser?.name || 'Sarah Jenkins'}
              </div>
              <div className="text-[10px] text-slate-400 capitalize">
                {adminUser?.role ? adminUser.role.replace('_', ' ') : 'Super Admin'}
              </div>
            </div>
            <i className="fa-solid fa-chevron-down text-[10px] text-slate-400" />
          </button>

          {profileOpen && (
            <div className="absolute right-0 mt-2 w-64 rounded-2xl bg-white border border-slate-200 shadow-xl p-4 z-50 space-y-3 animate-in fade-in zoom-in-95">
              <div className="pb-3 border-b border-slate-100">
                <div className="text-xs font-bold text-slate-900">{adminUser?.name || 'Sarah Jenkins'}</div>
                <div className="text-[11px] text-slate-400 truncate">{adminUser?.email || 'admin@meta-connector.app'}</div>
                <div className="mt-2">
                  <span
                    className={`inline-block px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wider border ${roleBadge(
                      adminUser?.role || 'super_admin'
                    )}`}
                  >
                    {adminUser?.role ? adminUser.role.replace('_', ' ') : 'Super Admin'}
                  </span>
                </div>
              </div>

              {/* RBAC Role Switcher (For testing permissions) */}
              {onRoleSwitch && (
                <div className="space-y-1.5">
                  <span className="text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                    Role Switcher (RBAC Test)
                  </span>
                  <div className="grid grid-cols-1 gap-1">
                    {(['super_admin', 'billing_admin', 'support_agent'] as AdminRole[]).map((r) => (
                      <button
                        key={r}
                        onClick={() => {
                          onRoleSwitch(r);
                          setProfileOpen(false);
                        }}
                        className={`text-left px-2.5 py-1.5 rounded-lg text-xs font-semibold flex items-center justify-between cursor-pointer ${
                          adminUser?.role === r ? 'bg-theme/10 text-theme font-bold' : 'hover:bg-slate-50 text-slate-600'
                        }`}
                      >
                        <span className="capitalize">{r.replace('_', ' ')}</span>
                        {adminUser?.role === r && <i className="fa-solid fa-check text-xs" />}
                      </button>
                    ))}
                  </div>
                </div>
              )}

              <div className="pt-2 border-t border-slate-100">
                <button
                  onClick={() => {
                    setProfileOpen(false);
                    onLogout();
                  }}
                  className="w-full text-left px-2.5 py-1.5 rounded-lg text-xs font-bold text-rose-600 hover:bg-rose-50 flex items-center gap-2 cursor-pointer"
                >
                  <i className="fa-solid fa-arrow-right-from-bracket text-xs" />
                  <span>Log Out of Admin Hub</span>
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </header>
  );
}
