"use client";

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

export default function TraineesListPage() {
  const [trainees, setTrainees] = useState<ResultRecord[]>([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");
  const [tradeCode, setTradeCode] = useState("");
  const [status, setStatus] = useState("");
  const [previewTrainee, setPreviewTrainee] = useState<ResultRecord | null>(null);

  const fetchTrainees = useCallback(async () => {
    setLoading(true);
    try {
      const params = new URLSearchParams();
      if (search) params.set("search", search);
      if (tradeCode) params.set("trade", tradeCode);
      if (status) params.set("status", status);
      params.set("limit", "200");

      const res = await fetch(`/api/admin/trainees?${params.toString()}`);
      const json = await res.json();
      if (json.ok) {
        setTrainees(json.items || []);
        setTotal(json.total || 0);
      }
    } catch (err) {
      console.error("Trainees fetch error:", err);
    } finally {
      setLoading(false);
    }
  }, [search, tradeCode, status]);

  useEffect(() => {
    const timer = setTimeout(() => {
      fetchTrainees();
    }, 250);
    return () => clearTimeout(timer);
  }, [fetchTrainees]);

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

    try {
      const res = await fetch(`/api/admin/trainees/${id}`, { method: "DELETE" });
      const json = await res.json();
      if (json.ok) {
        setTrainees((prev) => prev.filter((t) => t.id !== id));
        setTotal((prev) => Math.max(0, prev - 1));
      } else {
        alert(json.error || "Failed to delete");
      }
    } catch {
      alert("Delete failed");
    }
  }

  function exportCsv() {
    if (trainees.length === 0) {
      alert("No trainees to export.");
      return;
    }

    const headers = [
      "Registration No",
      "Trainee Name",
      "DOB",
      "Trade Code",
      "Trade Name",
      "Total Obtained",
      "Total Max",
      "Result Status",
    ];

    const rows = trainees.map((t) => [
      `"${t.regNo}"`,
      `"${t.candidateName}"`,
      `"${t.dob}"`,
      `"${t.tradeCode}"`,
      `"${t.tradeName}"`,
      t.totalObtained,
      t.totalMax,
      `"${t.resultStatus}"`,
    ]);

    const csvContent = "data:text/csv;charset=utf-8," + [headers.join(","), ...rows.map((r) => r.join(","))].join("\n");
    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", `Industrial_School_Results_${new Date().toISOString().slice(0, 10)}.csv`);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  }

  return (
    <div className="space-y-6">
      {/* Top Header */}
      <div className="flex flex-col justify-between gap-4 border-b border-ink/15 pb-4 md:flex-row md:items-center">
        <div>
          <h1 className="font-display text-2xl font-bold text-maroon-950 sm:text-3xl">
            Trainee Examination Results
          </h1>
          <p className="text-xs text-ink/60">
            Industrial School Common Examination July 2026 · Cutting &amp; Tailoring, Embroidery &amp; Needle Work, and TTC
          </p>
        </div>

        <div className="flex flex-wrap items-center gap-2.5">
          <button
            type="button"
            onClick={exportCsv}
            className="flex items-center gap-1.5 rounded-sm border border-gold-600 bg-gold-50 px-3.5 py-2 text-xs font-bold uppercase tracking-wider text-maroon-950 hover:bg-gold-100"
          >
            <span>📥</span> Export CSV
          </button>
          <Link
            href="/admin/import"
            className="flex items-center gap-1.5 rounded-sm border border-ink/20 bg-white px-3.5 py-2 text-xs font-bold uppercase tracking-wider text-ink hover:bg-ink/5"
          >
            <span>📁</span> Bulk CSV Import
          </Link>
          <Link
            href="/admin/trainees/new"
            className="flex items-center gap-1.5 rounded-sm bg-maroon-900 px-4 py-2 text-xs font-bold uppercase tracking-wider text-cream shadow-sm hover:bg-maroon-800"
          >
            <span>➕</span> Add New Result
          </Link>
        </div>
      </div>

      {/* Filter and Search Bar */}
      <div className="card-shadow flex flex-col gap-3 rounded-md border border-ink/15 bg-white p-4 sm:flex-row sm:items-center">
        {/* Search */}
        <div className="relative flex-1">
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Search by candidate name or registration number…"
            className="w-full rounded-sm border border-ink/25 bg-cream/30 px-3.5 py-2 pl-9 text-xs text-ink outline-none focus:border-maroon-900 focus:bg-white"
          />
          <svg
            className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-ink/40"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
        </div>

        {/* Trade Filter */}
        <div className="w-full sm:w-48">
          <select
            value={tradeCode}
            onChange={(e) => setTradeCode(e.target.value)}
            className="w-full rounded-sm border border-ink/25 bg-cream/30 px-3 py-2 text-xs text-ink outline-none focus:border-maroon-900 focus:bg-white"
          >
            <option value="">All Trades</option>
            {TRADES.map((t) => (
              <option key={t.code} value={t.code}>
                {t.code} — {t.name}
              </option>
            ))}
          </select>
        </div>

        {/* Status Filter */}
        <div className="w-full sm:w-36">
          <select
            value={status}
            onChange={(e) => setStatus(e.target.value)}
            className="w-full rounded-sm border border-ink/25 bg-cream/30 px-3 py-2 text-xs text-ink outline-none focus:border-maroon-900 focus:bg-white"
          >
            <option value="">All Statuses</option>
            <option value="PASS">PASS Only</option>
            <option value="FAIL">FAIL Only</option>
          </select>
        </div>

        {(search || tradeCode || status) && (
          <button
            type="button"
            onClick={() => {
              setSearch("");
              setTradeCode("");
              setStatus("");
            }}
            className="rounded-sm border border-ink/20 px-3 py-2 text-xs font-semibold text-ink/70 hover:bg-ink/5"
          >
            Reset
          </button>
        )}
      </div>

      {/* Trainees Data Table */}
      <div className="card-shadow overflow-hidden rounded-md border border-ink/15 bg-white">
        <div className="flex items-center justify-between border-b border-ink/10 bg-cream px-5 py-3 text-xs text-ink/70">
          <span>
            Showing <strong className="text-maroon-950">{trainees.length}</strong> of{" "}
            <strong className="text-maroon-950">{total}</strong> trainee records
          </span>
          <span className="font-mono text-[11px]">Industrial School Common Exam July 2026</span>
        </div>

        {loading ? (
          <div className="py-16 text-center text-xs text-ink/50">Fetching trainee records…</div>
        ) : trainees.length === 0 ? (
          <div className="py-16 text-center text-xs text-ink/50">
            No trainee records match your filter criteria.
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full border-collapse text-left text-xs">
              <thead>
                <tr className="border-b border-ink/15 bg-maroon-950 text-[10px] font-bold uppercase tracking-wider text-cream">
                  <th className="px-4 py-3">Registration No</th>
                  <th className="px-4 py-3">Trainee Name</th>
                  <th className="px-4 py-3">Trade Name</th>
                  <th className="px-4 py-3">DOB</th>
                  <th className="px-4 py-3 text-center">Marks Secured</th>
                  <th className="px-4 py-3 text-center">Result</th>
                  <th className="px-4 py-3 text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-ink/10">
                {trainees.map((t) => {
                  const passed = t.resultStatus === "PASS";
                  return (
                    <tr key={t.id} className="hover:bg-gold-50/40 transition-colors">
                      <td className="px-4 py-3 font-mono font-bold text-maroon-950">
                        {t.regNo}
                      </td>
                      <td className="px-4 py-3 font-bold text-ink">
                        {t.candidateName}
                      </td>
                      <td className="px-4 py-3">
                        <span className="inline-block rounded-xs bg-gold-100/80 px-2 py-0.5 text-[11px] font-bold text-maroon-950">
                          {t.tradeCode}
                        </span>
                        <span className="ml-1.5 text-xs text-ink/75">{t.tradeName}</span>
                      </td>
                      <td className="px-4 py-3 font-mono text-ink/70">{t.dob}</td>
                      <td className="px-4 py-3 text-center font-mono font-bold text-ink">
                        {t.totalObtained} / {t.totalMax}
                      </td>
                      <td className="px-4 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-4 py-3 text-right">
                        <div className="flex items-center justify-end gap-1.5">
                          <button
                            type="button"
                            onClick={() => setPreviewTrainee(t)}
                            title="Preview official result"
                            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`}
                            title="Edit marks"
                            className="rounded-xs border border-ink/20 bg-white px-2 py-1 text-[11px] font-semibold text-ink hover:bg-ink/5"
                          >
                            ✏️ Edit
                          </Link>
                          <button
                            type="button"
                            onClick={() => handleDelete(t.id, t.regNo)}
                            title="Delete result"
                            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>

      {/* Preview Result Modal */}
      {previewTrainee && (
        <div className="fixed inset-0 z-50 flex items-center justify-center overflow-y-auto bg-black/75 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">
                Examination Result · {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={() => window.print()}
              onSubmitAnother={() => setPreviewTrainee(null)}
            />
          </div>
        </div>
      )}
    </div>
  );
}
