"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import type { AdminDashboardStats, ResultRecord } from "@/lib/types";
import { EXAM, SCHOOL, TRADES } from "@/lib/constants";
import ResultCard from "@/components/ResultCard";
import LogoManager from "@/components/LogoManager";

export default function AdminDashboardPage() {
  const [stats, setStats] = useState<AdminDashboardStats | null>(null);
  const [recentTrainees, setRecentTrainees] = useState<ResultRecord[]>([]);
  const [loading, setLoading] = useState(true);
  const [previewTrainee, setPreviewTrainee] = useState<ResultRecord | null>(null);

  useEffect(() => {
    async function loadDashboard() {
      try {
        const [statsRes, traineesRes] = await Promise.all([
          fetch("/api/admin/stats"),
          fetch("/api/admin/trainees?limit=8"),
        ]);

        const statsJson = await statsRes.json();
        const traineesJson = await traineesRes.json();

        if (statsJson.ok) setStats(statsJson.data);
        if (traineesJson.ok) setRecentTrainees(traineesJson.items);
      } catch (err) {
        console.error("Dashboard fetch error:", err);
      } finally {
        setLoading(false);
      }
    }
    loadDashboard();
  }, []);

  async function handleDelete(id: number | string, regNo: string) {
    if (!confirm(`Are you sure you want to delete result for trainee ${regNo}?`)) return;

    try {
      const res = await fetch(`/api/admin/trainees/${id}`, { method: "DELETE" });
      const json = await res.json();
      if (json.ok) {
        setRecentTrainees((prev) => prev.filter((t) => t.id !== id));
        // Reload stats
        const sRes = await fetch("/api/admin/stats");
        const sJson = await sRes.json();
        if (sJson.ok) setStats(sJson.data);
      } else {
        alert(json.error || "Failed to delete");
      }
    } catch {
      alert("Delete failed");
    }
  }

  function handlePrint() {
    window.print();
  }

  return (
    <div className="space-y-8">
      {/* Top Banner */}
      <div className="flex flex-col justify-between gap-4 rounded-md border-2 border-maroon-900/20 bg-cream p-6 shadow-xs md:flex-row md:items-center">
        <div>
          <p className="text-[10px] font-bold uppercase tracking-[0.3em] text-maroon-800">
            {EXAM.title}
          </p>
          <h1 className="mt-1 font-display text-2xl font-bold text-maroon-950 sm:text-3xl">
            Examination Results Console
          </h1>
          <p className="mt-0.5 text-xs text-ink/65">
            {SCHOOL.fullName} · {SCHOOL.dept}
          </p>
        </div>

        <div className="flex flex-wrap gap-2.5">
          <Link
            href="/admin/trainees/new"
            className="flex items-center gap-1.5 rounded-sm bg-maroon-900 px-4 py-2.5 text-xs font-bold uppercase tracking-wider text-cream shadow-sm hover:bg-maroon-800"
          >
            <span>➕</span> Add New Result
          </Link>
          <Link
            href="/admin/import"
            className="flex items-center gap-1.5 rounded-sm border border-gold-600 bg-gold-50 px-4 py-2.5 text-xs font-bold uppercase tracking-wider text-maroon-950 hover:bg-gold-100"
          >
            <span>📁</span> Bulk CSV Import
          </Link>
          <a
            href="#logo-update-area"
            className="flex items-center gap-1.5 rounded-sm border border-maroon-900/30 bg-white px-4 py-2.5 text-xs font-bold uppercase tracking-wider text-maroon-950 hover:bg-cream"
          >
            <span>🏛️</span> Logo Update Area
          </a>
        </div>
      </div>

      {/* KPI Stats Overview */}
      <div className="grid grid-cols-2 gap-4 sm:grid-cols-2 lg:grid-cols-4">
        {/* Total Trainees */}
        <div className="card-shadow rounded-md border border-ink/15 bg-white p-5">
          <div className="flex items-center justify-between">
            <span className="text-[10px] font-bold uppercase tracking-[0.2em] text-ink/50">
              Total Trainees
            </span>
            <span className="rounded-full bg-maroon-100 px-2 py-0.5 text-xs font-bold text-maroon-900">
              Registered
            </span>
          </div>
          <p className="mt-2 font-display text-3xl font-black text-maroon-950">
            {loading ? "…" : stats?.totalTrainees || 0}
          </p>
          <p className="font-tamil mt-1 text-[11px] text-ink/45">மொத்த மாணவர்கள்</p>
        </div>

        {/* Total Passed */}
        <div className="card-shadow rounded-md border border-forest-600/30 bg-forest-50/40 p-5">
          <div className="flex items-center justify-between">
            <span className="text-[10px] font-bold uppercase tracking-[0.2em] text-forest-800">
              Total Passed
            </span>
            <span className="rounded-full bg-forest-100 px-2 py-0.5 text-xs font-bold text-forest-900">
              PASS
            </span>
          </div>
          <p className="mt-2 font-display text-3xl font-black text-forest-800">
            {loading ? "…" : stats?.totalPass || 0}
          </p>
          <p className="font-tamil mt-1 text-[11px] text-forest-700/60">வெற்றி பெற்றோர்</p>
        </div>

        {/* Total Failed */}
        <div className="card-shadow rounded-md border border-maroon-700/30 bg-maroon-50/40 p-5">
          <div className="flex items-center justify-between">
            <span className="text-[10px] font-bold uppercase tracking-[0.2em] text-maroon-800">
              Re-appear / Failed
            </span>
            <span className="rounded-full bg-maroon-100 px-2 py-0.5 text-xs font-bold text-maroon-900">
              FAIL
            </span>
          </div>
          <p className="mt-2 font-display text-3xl font-black text-maroon-800">
            {loading ? "…" : stats?.totalFail || 0}
          </p>
          <p className="font-tamil mt-1 text-[11px] text-maroon-700/60">மீண்டும் தேர்வு</p>
        </div>

        {/* Pass Percentage */}
        <div className="card-shadow rounded-md border border-gold-600/40 bg-gold-50/50 p-5">
          <div className="flex items-center justify-between">
            <span className="text-[10px] font-bold uppercase tracking-[0.2em] text-gold-900">
              Pass Rate %
            </span>
            <span className="rounded-full bg-gold-200 px-2 py-0.5 text-xs font-bold text-maroon-950">
              Rate
            </span>
          </div>
          <p className="mt-2 font-display text-3xl font-black text-maroon-950">
            {loading ? "…" : `${stats?.passPercentage || 0}%`}
          </p>
          <p className="font-tamil mt-1 text-[11px] text-gold-900/60">தேர்ச்சி சதவீதம்</p>
        </div>
      </div>

      {/* Trade Wise Stats Breakdown */}
      <div>
        <div className="flex items-center justify-between">
          <div>
            <h2 className="font-display text-lg font-bold text-maroon-950">
              Trades &amp; Courses Performance
            </h2>
            <p className="text-xs text-ink/60">Summary of the 3 official industrial trades</p>
          </div>
          <Link
            href="/admin/trades"
            className="text-xs font-bold uppercase tracking-wider text-maroon-900 hover:underline"
          >
            View Subject Criteria →
          </Link>
        </div>

        <div className="mt-4 grid gap-4 md:grid-cols-3">
          {TRADES.map((trade) => {
            const stat = stats?.tradeStats.find((s) => s.tradeCode === trade.code);
            const total = stat?.total || 0;
            const passed = stat?.passed || 0;
            const failed = stat?.failed || 0;
            const rate = total > 0 ? ((passed / total) * 100).toFixed(1) : "0.0";

            return (
              <div
                key={trade.code}
                className="card-shadow rounded-md border border-ink/15 bg-white p-5"
              >
                <div className="flex items-start justify-between gap-2">
                  <div>
                    <span className="font-display text-xl font-black text-gold-700">
                      {trade.code}
                    </span>
                    <h3 className="text-sm font-bold text-maroon-950">{trade.name}</h3>
                    <p className="font-tamil text-[11px] text-ink/50">{trade.tamil}</p>
                  </div>
                  <span className="rounded-xs bg-maroon-50 px-2 py-1 text-[10px] font-bold text-maroon-900">
                    {trade.totalSubjects} Subjects
                  </span>
                </div>

                <div className="mt-4 flex items-center justify-between border-t border-ink/10 pt-3 text-xs">
                  <div>
                    <span className="text-ink/50">Trainees: </span>
                    <span className="font-bold text-ink">{total}</span>
                  </div>
                  <div>
                    <span className="text-forest-700">Pass: </span>
                    <span className="font-bold text-forest-800">{passed}</span>
                  </div>
                  <div>
                    <span className="text-maroon-700">Fail: </span>
                    <span className="font-bold text-maroon-800">{failed}</span>
                  </div>
                </div>

                {/* Progress Bar */}
                <div className="mt-3 h-2 w-full overflow-hidden rounded-full bg-ink/10">
                  <div
                    className="h-full bg-forest-600 transition-all duration-500"
                    style={{ width: `${rate}%` }}
                  />
                </div>
                <p className="mt-1 text-right text-[10px] font-bold text-ink/50">
                  {rate}% Pass Rate
                </p>
              </div>
            );
          })}
        </div>
      </div>

      {/* Recent Trainees Table */}
      <div className="rounded-md border border-ink/15 bg-white p-6 shadow-sm">
        <div className="flex flex-col justify-between gap-4 border-b border-ink/10 pb-4 sm:flex-row sm:items-center">
          <div>
            <h2 className="font-display text-xl font-bold text-maroon-950">
              Recent Trainee Results
            </h2>
            <p className="text-xs text-ink/60">Latest published examination results</p>
          </div>
          <Link
            href="/admin/trainees"
            className="inline-flex items-center gap-1 rounded-sm bg-gold-500 px-4 py-2 text-xs font-bold uppercase tracking-wider text-maroon-950 hover:bg-gold-400"
          >
            View All Trainees ({stats?.totalTrainees || 0}) →
          </Link>
        </div>

        {loading ? (
          <div className="py-12 text-center text-xs text-ink/50">Loading database records…</div>
        ) : recentTrainees.length === 0 ? (
          <div className="py-12 text-center text-xs text-ink/50">
            No trainee records found. Click &quot;Add New Result&quot; to insert one.
          </div>
        ) : (
          <div className="mt-4 overflow-x-auto">
            <table className="w-full border-collapse text-left text-xs">
              <thead>
                <tr className="border-b border-ink/15 bg-cream text-[10px] font-bold uppercase tracking-wider text-ink/70">
                  <th className="px-3 py-3">Reg No</th>
                  <th className="px-3 py-3">Trainee Name</th>
                  <th className="px-3 py-3">Trade</th>
                  <th className="px-3 py-3">DOB</th>
                  <th className="px-3 py-3 text-center">Marks Secured</th>
                  <th className="px-3 py-3 text-center">Result</th>
                  <th className="px-3 py-3 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-ink/10">
                {recentTrainees.map((t) => {
                  const passed = t.resultStatus === "PASS";
                  return (
                    <tr key={t.id} className="hover:bg-gold-50/40">
                      <td className="px-3 py-3 font-mono font-bold text-maroon-950">{t.regNo}</td>
                      <td className="px-3 py-3 font-semibold text-ink">{t.candidateName}</td>
                      <td className="px-3 py-3">
                        <span className="rounded-xs bg-ink/5 px-2 py-0.5 text-[11px] font-medium text-ink">
                          {t.tradeCode}
                        </span>
                      </td>
                      <td className="px-3 py-3 font-mono text-ink/70">{t.dob}</td>
                      <td className="px-3 py-3 text-center font-mono font-bold text-ink">
                        {t.totalObtained} / {t.totalMax}
                      </td>
                      <td className="px-3 py-3 text-center">
                        <span
                          className={`inline-block rounded-xs px-2.5 py-0.5 text-[10px] font-bold ${
                            passed
                              ? "bg-forest-100 text-forest-900 border border-forest-600/30"
                              : "bg-maroon-100 text-maroon-900 border border-maroon-600/30"
                          }`}
                        >
                          {t.resultStatus}
                        </span>
                      </td>
                      <td className="px-3 py-3 text-right">
                        <div className="flex items-center justify-end gap-2">
                          <button
                            type="button"
                            onClick={() => setPreviewTrainee(t)}
                            className="rounded-xs bg-gold-100 px-2.5 py-1 text-[11px] font-bold text-maroon-950 hover:bg-gold-200"
                          >
                            👁️ View Result
                          </button>
                          <Link
                            href={`/admin/trainees/${t.id}/edit`}
                            className="rounded-xs border border-ink/20 px-2.5 py-1 text-[11px] font-bold text-ink hover:bg-ink/5"
                          >
                            ✏️ Edit
                          </Link>
                          <button
                            type="button"
                            onClick={() => handleDelete(t.id, t.regNo)}
                            className="rounded-xs border border-maroon-300 px-2 py-1 text-[11px] font-bold text-maroon-800 hover:bg-maroon-50"
                          >
                            🗑️
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Logo Update Area (Prominently featured and marked Note: Do Not Delete) */}
      <LogoManager />

      {/* Result Preview Modal */}
      {previewTrainee && (
        <div className="fixed inset-0 z-50 flex items-center justify-center overflow-y-auto bg-black/70 p-4 backdrop-blur-xs">
          <div className="relative max-h-[92vh] w-full max-w-4xl overflow-y-auto rounded-lg bg-white p-4 shadow-2xl">
            <div className="sticky top-0 z-30 mb-3 flex items-center justify-between rounded-md bg-maroon-950 px-4 py-2.5 text-cream">
              <span className="font-display text-sm font-bold">
                Live Result Preview · {previewTrainee.candidateName} ({previewTrainee.regNo})
              </span>
              <button
                type="button"
                onClick={() => setPreviewTrainee(null)}
                className="rounded-full bg-white/20 px-2.5 py-0.5 text-xs font-bold text-white hover:bg-white/30"
              >
                ✕ Close Preview
              </button>
            </div>

            <ResultCard
              data={previewTrainee}
              onPrint={handlePrint}
              onSubmitAnother={() => setPreviewTrainee(null)}
            />
          </div>
        </div>
      )}
    </div>
  );
}
