"use client";

import React, { useState, useEffect } from "react";
import { Navbar } from "@/components/Navbar";
import { Sidebar } from "@/components/Sidebar";
import { DashboardView } from "@/components/DashboardView";
import { PatientsView } from "@/components/PatientsView";
import { SettingsView } from "@/components/SettingsView";
import { JobsQueueView } from "@/components/JobsQueueView";
import { TestModeView } from "@/components/TestModeView";
import { LogsView } from "@/components/LogsView";
import { StandaloneSystemView } from "@/components/StandaloneSystemView";
import { InstallerWizardView } from "@/components/InstallerWizardView";
import { ScreenshotModal } from "@/components/ScreenshotModal";
import { ManualActionModal } from "@/components/ManualActionModal";
import { LoginView } from "@/components/LoginView";
import { Play, AlertTriangle, X, CheckCircle, RefreshCw } from "lucide-react";

export default function HomePage() {
  const [admin, setAdmin] = useState<any | null>(null);
  const [authChecked, setAuthChecked] = useState(false);
  const [activeTab, setActiveTab] = useState("dashboard");

  // Dashboard Data
  const [dashboardData, setDashboardData] = useState<any | null>(null);
  const [loading, setLoading] = useState(true);

  // Modals
  const [screenshotJob, setScreenshotJob] = useState<any | null>(null);
  const [manualJob, setManualJob] = useState<any | null>(null);
  const [showRunConfirm, setShowRunConfirm] = useState(false);
  const [actionNotice, setActionNotice] = useState<string | null>(null);

  // Check auth
  useEffect(() => {
    fetch("/api/auth/me")
      .then((res) => res.json())
      .then((data) => {
        if (data.authenticated) {
          setAdmin(data.admin);
        }
        setAuthChecked(true);
      })
      .catch(() => setAuthChecked(true));
  }, []);

  // Fetch Dashboard
  const fetchDashboardData = async () => {
    try {
      const res = await fetch("/api/dashboard");
      const data = await res.json();
      if (data.success) {
        setDashboardData(data);
      }
    } catch (e) {
      console.error(e);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (!admin) return;
    fetchDashboardData();
    const interval = setInterval(fetchDashboardData, 4000);
    return () => clearInterval(interval);
  }, [admin]);

  const showToast = (msg: string) => {
    setActionNotice(msg);
    setTimeout(() => setActionNotice(null), 4000);
  };

  const handleLogout = async () => {
    await fetch("/api/auth/logout", { method: "POST" });
    setAdmin(null);
  };

  const handleRunJob = async (jobId: number) => {
    showToast(`Executing serial job #${jobId}...`);
    try {
      const res = await fetch("/api/jobs/run", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ jobId }),
      });
      const data = await res.json();
      if (data.success) {
        showToast(`✓ Job #${jobId} completed successfully! Assigned: ${data.result?.serialNumber || "Success"}`);
      } else {
        showToast(`✕ Job #${jobId} failed: ${data.error}`);
      }
      fetchDashboardData();
    } catch (e) {
      showToast("Error executing job");
    }
  };

  const handleRunAll = async () => {
    setShowRunConfirm(false);
    showToast("Triggering sequential submission for all 5 scheduled serials...");
    try {
      const res = await fetch("/api/jobs/run", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ runAll: true }),
      });
      const data = await res.json();
      if (data.success) {
        showToast(`✓ Completed all ${data.results?.length || 5} appointment serials!`);
      } else {
        showToast(`✕ Execution error: ${data.error}`);
      }
      fetchDashboardData();
    } catch (e) {
      showToast("Execution failed");
    }
  };

  const handleRegenerate = async () => {
    showToast("Regenerating today's 5 appointment serials...");
    try {
      const res = await fetch("/api/jobs/regenerate", { method: "POST" });
      const data = await res.json();
      if (data.success) {
        showToast("✓ Today's 5 serial slots regenerated successfully!");
      }
      fetchDashboardData();
    } catch (e) {
      showToast("Regeneration failed");
    }
  };

  if (!authChecked) {
    return (
      <div className="min-h-screen bg-slate-950 flex items-center justify-center text-white font-mono text-xs">
        <RefreshCw className="w-5 h-5 animate-spin text-blue-500 mr-2" />
        Bootstrapping Auto Serial Engine...
      </div>
    );
  }

  if (!admin) {
    return <LoginView onLoginSuccess={(adm) => setAdmin(adm)} />;
  }

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100 flex flex-col font-sans selection:bg-blue-600 selection:text-white">
      {/* Toast Notice */}
      {actionNotice && (
        <div className="fixed top-16 right-6 z-50 p-4 rounded-xl bg-slate-900 border border-blue-500/40 text-xs font-semibold text-white shadow-2xl flex items-center gap-2.5 animate-in slide-in-from-top-4">
          <CheckCircle className="w-4 h-4 text-emerald-400 shrink-0" />
          <span>{actionNotice}</span>
        </div>
      )}

      {/* Navbar */}
      <Navbar
        admin={admin}
        onLogout={handleLogout}
        onTriggerRunNow={() => setShowRunConfirm(true)}
        onTriggerTestModal={() => setActiveTab("test")}
        activeTab={activeTab}
        setActiveTab={setActiveTab}
        automationEnabled={dashboardData?.config?.automationEnabled ?? true}
        startTime={dashboardData?.config?.startTime || "07:05"}
      />

      <div className="flex-1 flex flex-col lg:flex-row">
        {/* Sidebar */}
        <Sidebar
          activeTab={activeTab}
          setActiveTab={setActiveTab}
          pendingCount={dashboardData?.stats?.pending || 0}
          manualCount={dashboardData?.stats?.manualRequired || 0}
        />

        {/* Main Content Area */}
        <main className="flex-1 p-4 md:p-8 max-w-7xl mx-auto w-full">
          {loading && !dashboardData ? (
            <div className="py-24 text-center text-slate-500 text-xs">
              <RefreshCw className="w-6 h-6 animate-spin text-blue-500 mx-auto mb-2" />
              Loading system metrics...
            </div>
          ) : (
            <>
              {activeTab === "dashboard" && dashboardData && (
                <DashboardView
                  data={dashboardData}
                  onRefresh={fetchDashboardData}
                  onRunJob={handleRunJob}
                  onRunAll={() => setShowRunConfirm(true)}
                  onRegenerate={handleRegenerate}
                  onOpenScreenshot={(job) => setScreenshotJob(job)}
                  onOpenManualModal={(job) => setManualJob(job)}
                  setActiveTab={setActiveTab}
                />
              )}

              {activeTab === "patients" && (
                <PatientsView onPatientsUpdated={fetchDashboardData} />
              )}

              {activeTab === "settings" && (
                <SettingsView onSettingsSaved={fetchDashboardData} />
              )}

              {activeTab === "jobs" && (
                <JobsQueueView
                  onOpenScreenshot={(job) => setScreenshotJob(job)}
                  onOpenManualModal={(job) => setManualJob(job)}
                  onRunJob={handleRunJob}
                />
              )}

              {activeTab === "test" && <TestModeView />}

              {activeTab === "logs" && <LogsView />}

              {activeTab === "standalone" && <StandaloneSystemView />}

              {activeTab === "installer" && <InstallerWizardView />}
            </>
          )}
        </main>
      </div>

      {/* Screenshot Inspector Modal */}
      <ScreenshotModal
        isOpen={Boolean(screenshotJob)}
        onClose={() => setScreenshotJob(null)}
        job={screenshotJob}
      />

      {/* Manual Action Resolution Modal */}
      <ManualActionModal
        isOpen={Boolean(manualJob)}
        onClose={() => setManualJob(null)}
        job={manualJob}
        onResolved={fetchDashboardData}
      />

      {/* Run Now Confirmation Dialog */}
      {showRunConfirm && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm p-4">
          <div className="relative w-full max-w-md bg-slate-900 border border-slate-700 rounded-2xl p-6 shadow-2xl space-y-4">
            <div className="flex items-center gap-3">
              <div className="p-2.5 rounded-xl bg-blue-500/20 text-blue-400">
                <Play className="w-6 h-6 fill-current" />
              </div>
              <div>
                <h3 className="text-base font-bold text-white">Execute All 5 Serials Now?</h3>
                <p className="text-xs text-slate-400">Manual Immediate Trigger Confirmation</p>
              </div>
            </div>

            <p className="text-xs text-slate-300 leading-relaxed">
              This will launch the automation engine and sequentially submit all 5 pending appointments on the portal with the configured 1-minute interval.
            </p>

            <div className="flex items-center justify-end gap-3 pt-2">
              <button
                onClick={() => setShowRunConfirm(false)}
                className="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-slate-300 rounded-xl text-xs font-semibold"
              >
                Cancel
              </button>
              <button
                onClick={handleRunAll}
                className="px-5 py-2 bg-blue-600 hover:bg-blue-500 text-white rounded-xl text-xs font-bold flex items-center gap-1.5 shadow-lg shadow-blue-600/30"
              >
                <Play className="w-3.5 h-3.5 fill-current" /> Confirm &amp; Run 5 Serials
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
