/**
 * @license
 * SPDX-License-Identifier: Apache-2.0
 */

import { useState, useRef, useEffect, memo } from 'react';
import { Home, LogOut, PlusCircle, Database, LayoutDashboard, User, ShieldAlert, Sparkles, Layout, ClipboardList, Code, ChevronDown, Bell, Mail, MessageCircle, Check, CheckSquare, BellRing, Key, Menu, Cloud } from 'lucide-react';
import { User as UserType, AppNotification } from '../types';

interface NavbarProps {
  currentUser: UserType | null;
  activeTab: 'explore' | 'dashboard' | 'schema' | 'my-bookings' | 'users' | 'permissions' | 'profiling' | 'ci3-template' | 'operations' | 'ai-prediction' | 'superadmin' | 'cloud-storage';
  setActiveTab: (tab: 'explore' | 'dashboard' | 'schema' | 'my-bookings' | 'users' | 'permissions' | 'profiling' | 'ci3-template' | 'operations' | 'ai-prediction' | 'superadmin' | 'cloud-storage') => void;
  onOpenAuth: () => void;
  onOpenAddProperty: () => void;
  onLogout: () => void;
  devMode: boolean;
  setDevMode: (val: boolean) => void;
  notifications?: AppNotification[];
  onRefreshNotifications?: () => void;
  onToggleSidebar?: () => void;
  onChangePassword?: () => void;
}

export default memo(function Navbar({
  currentUser,
  activeTab,
  setActiveTab,
  onOpenAuth,
  onOpenAddProperty,
  onLogout,
  devMode,
  setDevMode,
  notifications = [],
  onRefreshNotifications,
  onToggleSidebar,
  onChangePassword,
}: NavbarProps) {
  const [isDevMenuOpen, setIsDevMenuOpen] = useState(false);
  const [isNotifOpen, setIsNotifOpen] = useState(false);
  
  const devMenuRef = useRef<HTMLDivElement>(null);
  const notifRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (devMenuRef.current && !devMenuRef.current.contains(event.target as Node)) {
        setIsDevMenuOpen(false);
      }
      if (notifRef.current && !notifRef.current.contains(event.target as Node)) {
        setIsNotifOpen(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  const handleMarkAsRead = async (id: string) => {
    try {
      const res = await fetch(`/api/notifications/${id}/read`, { method: 'POST' });
      if (res.ok && onRefreshNotifications) {
        onRefreshNotifications();
      }
    } catch (e) {
      console.error("Gagal menandai dibaca:", e);
    }
  };

  const handleMarkAllAsRead = async () => {
    if (!currentUser) return;
    try {
      const res = await fetch('/api/notifications/read-all', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId: currentUser.id })
      });
      if (res.ok && onRefreshNotifications) {
        onRefreshNotifications();
      }
    } catch (e) {
      console.error("Gagal menandai semua dibaca:", e);
    }
  };

  return (
    <nav className="bg-white border-b border-gray-100 sticky top-0 z-40">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div className="flex justify-between h-16">
          <div className="flex items-center space-x-8">
            {/* Toggle Sidebar & Mobile Branding */}
            <div className="flex items-center space-x-3">
              {currentUser ? (
                <button
                  onClick={onToggleSidebar}
                  className="p-2 hover:bg-gray-100 rounded-lg text-gray-500 focus:outline-none cursor-pointer flex items-center justify-center transition-colors border border-gray-200"
                  title="Sembunyikan/Tampilkan Menu Samping"
                >
                  <Menu className="h-5 w-5" />
                </button>
              ) : (
                <div 
                  className="flex items-center cursor-pointer space-x-2 mr-4"
                  onClick={() => setActiveTab('explore')}
                >
                  <div className="bg-blue-600 text-white h-8 w-8 rounded-lg flex items-center justify-center font-black shadow-md tracking-tight">
                    P
                  </div>
                  <span className="font-sans font-extrabold text-lg tracking-tight text-gray-900">
                    Property<span className="text-blue-600">Hub</span>
                  </span>
                </div>
              )}
              
              {currentUser && (
                <div 
                  className="flex items-center cursor-pointer space-x-2 md:hidden"
                  onClick={() => setActiveTab('explore')}
                >
                  <span className="font-sans font-bold text-lg tracking-tight text-gray-900">
                    Property<span className="text-blue-600">Hub</span>
                  </span>
                </div>
              )}
            </div>

            {/* Nav Links */}
            <div className="hidden md:flex space-x-1 items-center">
              <button
                onClick={() => setActiveTab('explore')}
                className={`px-3 py-2 rounded-md text-sm font-medium transition-colors cursor-pointer ${
                  activeTab === 'explore'
                    ? 'bg-blue-50 text-blue-600'
                    : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                }`}
              >
                Jelajah Properti
              </button>

              {currentUser && (
                <button
                  onClick={() => setActiveTab('my-bookings')}
                  className={`px-3 py-2 rounded-md text-sm font-medium transition-colors cursor-pointer ${
                    activeTab === 'my-bookings'
                      ? 'bg-blue-50 text-blue-600'
                      : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                  }`}
                >
                  Transaksi Saya
                </button>
              )}

              {currentUser && ['owner', 'superadmin', 'admin'].includes(currentUser.role) && (
                <>
                  <button
                    onClick={() => setActiveTab('dashboard')}
                    className={`px-3 py-2 rounded-md text-sm font-medium flex items-center space-x-1.5 transition-colors cursor-pointer ${
                      activeTab === 'dashboard'
                        ? 'bg-blue-50 text-blue-600'
                        : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                    }`}
                  >
                    <LayoutDashboard className="h-4 w-4" />
                    <span>Dashboard Pengelola</span>
                  </button>

                  <button
                    onClick={() => setActiveTab('operations')}
                    className={`px-3 py-2 rounded-md text-sm font-medium flex items-center space-x-1.5 transition-colors cursor-pointer ${
                      activeTab === 'operations'
                        ? 'bg-blue-50 text-blue-600'
                        : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                    }`}
                  >
                    <ClipboardList className="h-4 w-4 text-emerald-500" />
                    <span>Pusat Operasional</span>
                  </button>

                  {currentUser.role === 'superadmin' && (
                    <button
                      onClick={() => setActiveTab('superadmin')}
                      className={`px-3 py-2 rounded-md text-sm font-medium flex items-center space-x-1.5 transition-colors cursor-pointer ${
                        activeTab === 'superadmin'
                          ? 'bg-indigo-50 text-indigo-700 font-extrabold border border-indigo-100/50'
                          : 'text-indigo-600 hover:text-indigo-900 hover:bg-indigo-50/50 font-bold'
                      }`}
                    >
                      <ShieldAlert className="h-4 w-4 text-indigo-600" />
                      <span>Konsol Superadmin</span>
                    </button>
                  )}
                </>
              )}

              {/* Developer & Architecture Tools Dropdown */}
              {devMode && (
                <div className="relative" ref={devMenuRef}>
                  <button
                    onClick={() => setIsDevMenuOpen(!isDevMenuOpen)}
                    className={`px-3 py-2 rounded-md text-sm font-medium flex items-center space-x-1.5 transition-colors cursor-pointer ${
                      ['schema', 'users', 'permissions', 'profiling', 'ci3-template', 'ai-prediction', 'cloud-storage'].includes(activeTab)
                        ? 'bg-blue-50 text-blue-600 font-semibold border border-blue-100/50'
                        : 'text-gray-600 hover:text-gray-900 hover:bg-gray-50'
                    }`}
                  >
                    <Code className="h-4 w-4 text-blue-500 animate-pulse" />
                    <span>Arsitektur & DevTools</span>
                    <ChevronDown className={`h-3 w-3 transition-transform duration-200 ${isDevMenuOpen ? 'rotate-180' : ''}`} />
                  </button>

                  {isDevMenuOpen && (
                    <div className="absolute left-0 mt-1.5 w-64 bg-white border border-gray-100 rounded-xl shadow-lg py-2 z-50 animate-in fade-in slide-in-from-top-1 duration-150">
                      <div className="px-3 py-1.5 text-[10px] font-bold text-gray-400 uppercase tracking-wider border-b border-gray-50 mb-1">
                        Dokumentasi & Simulasi
                      </div>

                      <button
                        onClick={() => {
                          setActiveTab('schema');
                          setIsDevMenuOpen(false);
                        }}
                        className={`w-full px-4 py-2.5 text-xs text-left flex items-center space-x-2.5 transition-colors hover:bg-gray-50 cursor-pointer ${
                          activeTab === 'schema' ? 'bg-blue-50/50 text-blue-600 font-semibold' : 'text-gray-700'
                        }`}
                      >
                        <Database className="h-4 w-4 text-blue-500" />
                        <div className="flex flex-col text-left">
                          <span>MySQL & CI3 Schema</span>
                          <span className="text-[10px] text-gray-400 font-normal">Struktur database fisik & skema</span>
                        </div>
                      </button>

                      <button
                        onClick={() => {
                          setActiveTab('users');
                          setIsDevMenuOpen(false);
                        }}
                        className={`w-full px-4 py-2.5 text-xs text-left flex items-center space-x-2.5 transition-colors hover:bg-gray-50 cursor-pointer ${
                          activeTab === 'users' ? 'bg-blue-50/50 text-blue-600 font-semibold' : 'text-gray-700'
                        }`}
                      >
                        <ShieldAlert className="h-4 w-4 text-red-500" />
                        <div className="flex flex-col text-left">
                          <span>User Management (RBAC)</span>
                          <span className="text-[10px] text-gray-400 font-normal">Simulasi multi-role & hak akses</span>
                        </div>
                      </button>

                      <button
                        onClick={() => {
                          setActiveTab('permissions');
                          setIsDevMenuOpen(false);
                        }}
                        className={`w-full px-4 py-2.5 text-xs text-left flex items-center space-x-2.5 transition-colors hover:bg-gray-50 cursor-pointer ${
                          activeTab === 'permissions' ? 'bg-blue-50/50 text-blue-600 font-semibold' : 'text-gray-700'
                        }`}
                      >
                        <Key className="h-4 w-4 text-amber-500" />
                        <div className="flex flex-col text-left">
                          <span>Master Hak Izin (Permissions)</span>
                          <span className="text-[10px] text-gray-400 font-normal">Konfigurasi kunci verifikasi global</span>
                        </div>
                      </button>

                      <button
                        onClick={() => {
                          setActiveTab('profiling');
                          setIsDevMenuOpen(false);
                        }}
                        className={`w-full px-4 py-2.5 text-xs text-left flex items-center space-x-2.5 transition-colors hover:bg-gray-50 cursor-pointer ${
                          activeTab === 'profiling' ? 'bg-blue-50/50 text-blue-600 font-semibold' : 'text-gray-700'
                        }`}
                      >
                        <Sparkles className="h-4 w-4 text-indigo-500" />
                        <div className="flex flex-col text-left">
                          <span>Profiling & AI Insights</span>
                          <span className="text-[10px] text-gray-400 font-normal">Rekomendasi taktik & analisis AI</span>
                        </div>
                      </button>

                      <button
                        onClick={() => {
                          setActiveTab('ci3-template');
                          setIsDevMenuOpen(false);
                        }}
                        className={`w-full px-4 py-2.5 text-xs text-left flex items-center space-x-2.5 transition-colors hover:bg-gray-50 cursor-pointer ${
                          activeTab === 'ci3-template' ? 'bg-blue-50/50 text-blue-600 font-semibold' : 'text-gray-700'
                        }`}
                      >
                        <Layout className="h-4 w-4 text-orange-500" />
                        <div className="flex flex-col text-left">
                          <span>Boilerplate CI3 & AdminLTE3</span>
                          <span className="text-[10px] text-gray-400 font-normal">File view, controller, model asli</span>
                        </div>
                      </button>

                      <button
                        onClick={() => {
                          setActiveTab('ai-prediction');
                          setIsDevMenuOpen(false);
                        }}
                        className={`w-full px-4 py-2.5 text-xs text-left flex items-center space-x-2.5 transition-colors hover:bg-gray-50 cursor-pointer ${
                          activeTab === 'ai-prediction' ? 'bg-blue-50/50 text-blue-600 font-semibold' : 'text-gray-700'
                        }`}
                      >
                        <Sparkles className="h-4 w-4 text-indigo-500 animate-pulse" />
                        <div className="flex flex-col text-left">
                          <span>Prediksi & Keputusan AI/ML</span>
                          <span className="text-[10px] text-gray-400 font-normal">Simulasi harga, okupansi, KPR & breakdown</span>
                        </div>
                      </button>

                      <button
                        onClick={() => {
                          setActiveTab('cloud-storage');
                          setIsDevMenuOpen(false);
                        }}
                        className={`w-full px-4 py-2.5 text-xs text-left flex items-center space-x-2.5 transition-colors hover:bg-gray-50 cursor-pointer ${
                          activeTab === 'cloud-storage' ? 'bg-blue-50/50 text-blue-600 font-semibold' : 'text-gray-700'
                        }`}
                      >
                        <Cloud className="h-4 w-4 text-sky-500" />
                        <div className="flex flex-col text-left">
                          <span>Cloud Storage & Google Drive</span>
                          <span className="text-[10px] text-gray-400 font-normal">Ekspor ZIP & upload Google Drive / Dropbox / S3</span>
                        </div>
                      </button>
                    </div>
                  )}
                </div>
              )}
              </div>
            </div>

          <div className="flex items-center space-x-4">
            {/* Elegant Dev Mode Toggle Switch */}
            <button
              onClick={() => {
                const newVal = !devMode;
                setDevMode(newVal);
                localStorage.setItem('devMode', String(newVal));
                // If turning OFF and currently on a dev tab, route back to explore
                if (!newVal && ['schema', 'users', 'permissions', 'profiling', 'ci3-template', 'ai-prediction', 'cloud-storage'].includes(activeTab)) {
                  setActiveTab('explore');
                }
              }}
              className={`px-3 py-1.5 rounded-full text-[10px] font-bold tracking-wider uppercase transition-all flex items-center space-x-1.5 border cursor-pointer ${
                devMode 
                  ? 'bg-emerald-50 text-emerald-700 border-emerald-200 hover:bg-emerald-100/80 shadow-xs' 
                  : 'bg-gray-50 text-gray-400 border-gray-200 hover:bg-gray-100 hover:text-gray-600'
              }`}
              title="Aktifkan/Nonaktifkan Alat Pengembang & Arsitektur Sistem"
            >
              <span className={`h-1.5 w-1.5 rounded-full ${devMode ? 'bg-emerald-500 animate-pulse' : 'bg-gray-400'}`}></span>
              <span>Dev Mode: {devMode ? 'ON' : 'OFF'}</span>
            </button>

            {currentUser && ['owner', 'superadmin', 'admin'].includes(currentUser.role) && (
              <button
                onClick={onOpenAddProperty}
                className="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium flex items-center space-x-1.5 shadow-sm transition-colors cursor-pointer"
              >
                <PlusCircle className="h-4 w-4" />
                <span>Daftarkan Properti</span>
              </button>
            )}

            {/* Notification Bell with Dropdown */}
            {currentUser && (
              <div className="relative" ref={notifRef}>
                <button
                  onClick={() => setIsNotifOpen(!isNotifOpen)}
                  className={`p-2 rounded-full border transition-all cursor-pointer relative ${
                    isNotifOpen
                      ? 'bg-blue-50 border-blue-200 text-blue-600 shadow-xs'
                      : 'bg-gray-50 border-gray-200 text-gray-500 hover:text-gray-800 hover:bg-gray-100'
                  }`}
                  title="Pemberitahuan & Notifikasi"
                >
                  <Bell className="h-4.5 w-4.5" />
                  {notifications.filter(n => !n.read).length > 0 && (
                    <span className="absolute -top-1 -right-1 bg-red-500 text-white font-bold text-[9px] h-4 w-4 flex items-center justify-center rounded-full shadow-sm animate-pulse">
                      {notifications.filter(n => !n.read).length}
                    </span>
                  )}
                </button>

                {isNotifOpen && (
                  <div className="absolute right-0 mt-2 w-80 bg-white border border-gray-100 rounded-2xl shadow-xl z-50 overflow-hidden transform origin-top-right transition-all">
                    {/* Header */}
                    <div className="p-4 border-b border-gray-50 flex items-center justify-between bg-gray-50/50">
                      <div className="flex items-center space-x-1.5">
                        <BellRing className="h-4 w-4 text-blue-600" />
                        <span className="font-sans font-bold text-xs text-gray-800">Notifikasi</span>
                        <span className="bg-blue-100 text-blue-800 text-[10px] px-1.5 py-0.5 rounded-full font-bold">
                          {notifications.filter(n => !n.read).length} Baru
                        </span>
                      </div>
                      {notifications.filter(n => !n.read).length > 0 && (
                        <button
                          onClick={handleMarkAllAsRead}
                          className="text-[10px] text-blue-600 hover:text-blue-800 font-bold flex items-center space-x-1 cursor-pointer"
                        >
                          <CheckSquare className="h-3 w-3" />
                          <span>Baca Semua</span>
                        </button>
                      )}
                    </div>

                    {/* Notification list */}
                    <div className="max-h-64 overflow-y-auto divide-y divide-gray-50">
                      {notifications.length === 0 ? (
                        <div className="p-6 text-center text-gray-400 text-xs">
                          Tidak ada notifikasi baru.
                        </div>
                      ) : (
                        notifications.map((notif) => (
                          <div
                            key={notif.id}
                            onClick={() => handleMarkAsRead(notif.id)}
                            className={`p-3 text-left transition-colors cursor-pointer hover:bg-gray-50/80 relative flex flex-col gap-1.5 ${
                              !notif.read ? 'bg-blue-50/10 border-l-2 border-blue-500 pl-2.5' : ''
                            }`}
                          >
                            <div className="flex items-start justify-between gap-2">
                              <span className={`font-sans font-semibold text-xs text-gray-900 ${!notif.read ? 'text-blue-900' : ''}`}>
                                {notif.title}
                              </span>
                              <span className="text-[9px] text-gray-400 shrink-0 font-mono">
                                {notif.createdAt}
                              </span>
                            </div>
                            <p className="text-[11px] text-gray-500 line-clamp-2 leading-relaxed">
                              {notif.message}
                            </p>
                            
                            {/* Dispatched channels status */}
                            <div className="flex items-center gap-2 mt-1">
                              {notif.channels?.email?.sent && (
                                <span className="inline-flex items-center space-x-1 text-[9px] bg-emerald-50 text-emerald-700 px-1.5 py-0.5 rounded border border-emerald-100 font-medium">
                                  <Mail className="h-2.5 w-2.5" />
                                  <span>Email Terkirim</span>
                                </span>
                              )}
                              {notif.channels?.whatsapp?.sent && (
                                <span className="inline-flex items-center space-x-1 text-[9px] bg-teal-50 text-teal-700 px-1.5 py-0.5 rounded border border-teal-100 font-medium">
                                  <MessageCircle className="h-2.5 w-2.5" />
                                  <span>WA Dispatched</span>
                                </span>
                              )}
                            </div>
                          </div>
                        ))
                      )}
                    </div>
                  </div>
                )}
              </div>
            )}

            {currentUser ? (
              <div className="flex items-center space-x-3 bg-gray-50 py-1.5 pl-3 pr-2.5 rounded-full border border-gray-100">
                <div className="flex flex-col text-right">
                  <span className="text-xs font-semibold text-gray-800 line-clamp-1 max-w-[120px]">
                    {currentUser.fullName}
                  </span>
                  <span className="text-[10px] uppercase tracking-wider text-gray-400 font-bold">
                    {currentUser.role === 'superadmin' ? 'Super Admin' : currentUser.role === 'admin' ? 'Admin Properti' : currentUser.role === 'owner' ? 'Host/Pemilik' : 'Tamu/Guest'}
                  </span>
                </div>
                {onChangePassword && (
                  <button
                    onClick={onChangePassword}
                    title="Ubah Sandi"
                    className="bg-white hover:bg-blue-50 text-gray-500 hover:text-blue-600 p-1.5 rounded-full border border-gray-200 transition-colors cursor-pointer"
                  >
                    <Key className="h-4 w-4" />
                  </button>
                )}
                <button
                  onClick={onLogout}
                  title="Keluar"
                  className="bg-white hover:bg-red-50 text-gray-500 hover:text-red-600 p-1.5 rounded-full border border-gray-200 transition-colors cursor-pointer"
                >
                  <LogOut className="h-4 w-4" />
                </button>
              </div>
            ) : (
              <button
                onClick={onOpenAuth}
                className="border border-gray-300 hover:border-blue-600 hover:text-blue-600 text-gray-700 px-4 py-2 rounded-lg text-sm font-medium flex items-center space-x-1.5 transition-colors cursor-pointer"
              >
                <User className="h-4 w-4" />
                <span>Masuk / Daftar</span>
              </button>
            )}
          </div>
        </div>
      </div>
    </nav>
  );
});
