"use client";

import React, { useState, useEffect } from "react";
import {
  Clock,
  Play,
  FlaskConical,
  Download,
  Bell,
  CheckCircle,
  AlertTriangle,
  LogOut,
  Shield,
  RefreshCw,
  ExternalLink,
  ChevronDown,
} from "lucide-react";

interface NavbarProps {
  admin: { name: string; username: string; email: string; role?: string } | null;
  onLogout: () => void;
  onTriggerRunNow: () => void;
  onTriggerTestModal: () => void;
  activeTab: string;
  setActiveTab: (tab: string) => void;
  automationEnabled: boolean;
  startTime: string;
}

export const Navbar: React.FC<NavbarProps> = ({
  admin,
  onLogout,
  onTriggerRunNow,
  onTriggerTestModal,
  activeTab,
  setActiveTab,
  automationEnabled,
  startTime,
}) => {
  const [dhakaTime, setDhakaTime] = useState<string>("");
  const [notifications, setNotifications] = useState<any[]>([]);
  const [showNotifications, setShowNotifications] = useState(false);
  const [unreadCount, setUnreadCount] = useState(0);
  const [downloadingZip, setDownloadingZip] = useState(false);

  // Live Dhaka Clock
  useEffect(() => {
    const updateTime = () => {
      const now = new Date();
      const timeStr = new Intl.DateTimeFormat("en-US", {
        timeZone: "Asia/Dhaka",
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit",
        hour12: true,
      }).format(now);
      setDhakaTime(timeStr);
    };

    updateTime();
    const timer = setInterval(updateTime, 1000);
    return () => clearInterval(timer);
  }, []);

  // Fetch notifications
  const fetchNotifications = async () => {
    try {
      const res = await fetch("/api/notifications");
      const data = await res.json();
      if (data.success && data.notifications) {
        setNotifications(data.notifications);
        setUnreadCount(data.notifications.filter((n: any) => !n.isRead).length);
      }
    } catch {}
  };

  useEffect(() => {
    fetchNotifications();
    const interval = setInterval(fetchNotifications, 10000);
    return () => clearInterval(interval);
  }, []);

  const handleDownloadZip = async () => {
    setDownloadingZip(true);
    try {
      const response = await fetch("/api/download-zip");
      if (!response.ok) throw new Error("Download failed");
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = "auto-appointment-serial-system-production.zip";
      document.body.appendChild(a);
      a.click();
      a.remove();
      window.URL.revokeObjectURL(url);
    } catch (e) {
      alert("Failed to download project ZIP. Please try again.");
    } finally {
      setDownloadingZip(false);
    }
  };

  const markAllNotificationsRead = async () => {
    try {
      await fetch("/api/notifications", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ markAllRead: true }),
      });
      setUnreadCount(0);
      setNotifications((prev) => prev.map((n) => ({ ...n, isRead: true })));
    } catch {}
  };

  return (
    <header className="sticky top-0 z-40 bg-slate-900/95 backdrop-blur-md border-b border-slate-800 px-4 lg:px-8 py-3 transition-all">
      <div className="flex items-center justify-between gap-4">
        {/* Left: Brand & Timezone Clock */}
        <div className="flex items-center gap-6">
          <div className="flex items-center gap-3 cursor-pointer" onClick={() => setActiveTab("dashboard")}>
            <div className="w-10 h-10 rounded-xl bg-gradient-to-tr from-blue-600 to-cyan-500 flex items-center justify-center text-white font-black shadow-lg shadow-blue-500/25">
              5S
            </div>
            <div>
              <h1 className="text-base font-extrabold tracking-tight text-white flex items-center gap-2">
                AUTO SERIAL <span className="text-xs px-2 py-0.5 rounded-full bg-blue-500/20 text-blue-400 font-semibold border border-blue-500/30">v1.0</span>
              </h1>
              <p className="text-[11px] text-slate-400 hidden sm:block">
                5 Serials / 1-Min Interval Daily Engine
              </p>
            </div>
          </div>

          {/* Live Bangladesh Time Clock */}
          <div className="hidden md:flex items-center gap-2.5 px-3 py-1.5 rounded-xl bg-slate-800/80 border border-slate-700/80 text-xs">
            <Clock className="w-4 h-4 text-cyan-400 animate-spin-slow" />
            <div>
              <div className="text-[10px] text-slate-400 font-medium leading-none">ASIA/DHAKA TIME</div>
              <div className="text-sm font-mono font-bold text-white tracking-wider">{dhakaTime || "--:--:--"}</div>
            </div>
            <div className="h-5 w-px bg-slate-700 mx-1" />
            <div className="flex items-center gap-1.5">
              <span
                className={`w-2 h-2 rounded-full ${
                  automationEnabled ? "bg-emerald-400 animate-pulse" : "bg-amber-400"
                }`}
              />
              <span className="text-[11px] font-semibold text-slate-300">
                {automationEnabled ? "ACTIVE" : "PAUSED"}
              </span>
            </div>
          </div>
        </div>

        {/* Right: Actions & User */}
        <div className="flex items-center gap-2.5">
          {/* Test Mode Trigger */}
          <button
            onClick={onTriggerTestModal}
            className="hidden sm:inline-flex items-center gap-1.5 px-3 py-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-200 border border-slate-700 text-xs font-semibold transition-all hover:scale-[1.02]"
            title="Inspect form fields without submitting"
          >
            <FlaskConical className="w-3.5 h-3.5 text-purple-400" />
            <span>Test Appointment</span>
          </button>

          {/* Run Now Trigger */}
          <button
            onClick={onTriggerRunNow}
            className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-lg bg-blue-600 hover:bg-blue-500 text-white text-xs font-bold shadow-md shadow-blue-600/30 transition-all hover:scale-[1.02]"
          >
            <Play className="w-3.5 h-3.5 fill-current" />
            <span>Run Now</span>
          </button>

          {/* Download Complete ZIP */}
          <button
            onClick={handleDownloadZip}
            disabled={downloadingZip}
            className="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-semibold shadow-md shadow-emerald-600/20 transition-all hover:scale-[1.02] disabled:opacity-50"
            title="Download full standalone project ZIP (PHP, MySQL, Playwright worker)"
          >
            <Download className={`w-3.5 h-3.5 ${downloadingZip ? "animate-bounce" : ""}`} />
            <span className="hidden md:inline">{downloadingZip ? "Zipping..." : "Download ZIP"}</span>
          </button>

          {/* Notifications Dropdown */}
          <div className="relative">
            <button
              onClick={() => setShowNotifications(!showNotifications)}
              className="relative p-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 transition-colors border border-slate-700"
            >
              <Bell className="w-4 h-4" />
              {unreadCount > 0 && (
                <span className="absolute -top-1 -right-1 w-4 h-4 rounded-full bg-rose-500 text-[10px] font-bold text-white flex items-center justify-center">
                  {unreadCount}
                </span>
              )}
            </button>

            {showNotifications && (
              <div className="absolute right-0 mt-2 w-80 bg-slate-900 border border-slate-700 rounded-xl shadow-2xl overflow-hidden z-50 animate-in fade-in slide-in-from-top-2">
                <div className="p-3 border-b border-slate-800 flex items-center justify-between bg-slate-950">
                  <span className="text-xs font-bold text-white flex items-center gap-1.5">
                    <Bell className="w-3.5 h-3.5 text-blue-400" /> Notifications
                  </span>
                  {unreadCount > 0 && (
                    <button
                      onClick={markAllNotificationsRead}
                      className="text-[10px] text-blue-400 hover:underline"
                    >
                      Mark all read
                    </button>
                  )}
                </div>
                <div className="max-h-72 overflow-y-auto divide-y divide-slate-800">
                  {notifications.length === 0 ? (
                    <div className="p-4 text-center text-xs text-slate-500">No notifications</div>
                  ) : (
                    notifications.map((n) => (
                      <div
                        key={n.id}
                        className={`p-3 text-xs ${n.isRead ? "bg-slate-900 text-slate-400" : "bg-slate-800/40 text-slate-200"}`}
                      >
                        <div className="font-semibold text-white mb-0.5">{n.title}</div>
                        <p className="line-clamp-2 text-[11px] text-slate-300">{n.message}</p>
                        <div className="mt-1 text-[10px] text-slate-500">
                          {new Date(n.createdAt).toLocaleTimeString("en-US", { timeZone: "Asia/Dhaka" })}
                        </div>
                      </div>
                    ))
                  )}
                </div>
              </div>
            )}
          </div>

          {/* Admin Avatar & Logout */}
          <div className="flex items-center gap-2 pl-2 border-l border-slate-800">
            <div className="hidden lg:block text-right">
              <div className="text-xs font-bold text-slate-200">{admin?.name || "Administrator"}</div>
              <div className="text-[10px] text-slate-500 font-mono">@{admin?.username || "admin"}</div>
            </div>
            <button
              onClick={onLogout}
              className="p-2 text-slate-400 hover:text-rose-400 hover:bg-slate-800 rounded-lg transition-colors"
              title="Logout"
            >
              <LogOut className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>
    </header>
  );
};
