"use client";
import { API, authFetch } from "@/lib/api";

import { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { GraduationCap, Plus, Search, Users, Calendar, X, CheckCircle, Trash2, ChevronDown, UserCheck } from "lucide-react";
import { cn } from "@/lib/utils";

interface TrainingAttendee {
  employeeId: string;
  status: string;
  employee: { firstName: string; lastName: string; employeeId: string };
}

interface Training {
  id: string;
  title: string;
  type: string;
  date: string;
  instructor: string;
  attendees: TrainingAttendee[];
  _count: { attendees: number };
}

const TYPE_STYLE: Record<string, { badge: string; card: string }> = {
  "Safety":      { badge: "bg-red-50 text-red-700 ring-red-600/20",     card: "border-red-100" },
  "Orientation": { badge: "bg-blue-50 text-blue-700 ring-blue-600/20",  card: "border-blue-100" },
  "Skill Up":    { badge: "bg-emerald-50 text-emerald-700 ring-emerald-600/20", card: "border-emerald-100" },
};

export default function TrainingPage() {
  const [trainings, setTrainings] = useState<Training[]>([]);
  const [employees, setEmployees] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSlideOverOpen, setIsSlideOverOpen] = useState(false);
  const [isAttendanceModalOpen, setIsAttendanceModalOpen] = useState(false);
  const [selectedTraining, setSelectedTraining] = useState<Training | null>(null);
  const [saving, setSaving] = useState(false);
  const [loggingAttendance, setLoggingAttendance] = useState(false);

  const [formData, setFormData] = useState({ title: "", type: "Safety", date: new Date().toISOString().split("T")[0], instructor: "" });
  const [searchQuery, setSearchQuery] = useState("");
  const [filterType, setFilterType] = useState("All");

  // Attendance modal state — multi-select with search
  const [attEmpSearch, setAttEmpSearch] = useState("");
  const [attEmpDropOpen, setAttEmpDropOpen] = useState(false);
  const [selectedAttendees, setSelectedAttendees] = useState<Set<string>>(new Set());
  const attDropRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    const h = (e: MouseEvent) => { if (attDropRef.current && !attDropRef.current.contains(e.target as Node)) setAttEmpDropOpen(false); };
    document.addEventListener("mousedown", h);
    return () => document.removeEventListener("mousedown", h);
  }, []);

  const fetchTrainings = async () => {
    try {
      setIsLoading(true);
      const res = await authFetch(`${API}/dash/training`);
      const data = await res.json();
      if (res.ok && Array.isArray(data)) setTrainings(data);
    } catch (e) { console.error(e); }
    finally { setIsLoading(false); }
  };

  const fetchEmployees = async () => {
    try {
      const res = await authFetch(`${API}/dash/employees?limit=1000`);
      const raw = await res.json();
      if (res.ok) setEmployees(Array.isArray(raw) ? raw : (raw.employees ?? []));
    } catch (e) { console.error(e); }
  };

  useEffect(() => { fetchTrainings(); fetchEmployees(); }, []);

  const handleCreate = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      const res = await authFetch(`${API}/dash/training`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });
      if (!res.ok) { alert("Failed to schedule session."); return; }
      setIsSlideOverOpen(false);
      setFormData({ title: "", type: "Safety", date: new Date().toISOString().split("T")[0], instructor: "" });
      fetchTrainings();
    } catch (e) { console.error(e); }
    finally { setSaving(false); }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Delete this training session?")) return;
    await authFetch(`${API}/dash/training/${id}`, { method: "DELETE" });
    fetchTrainings();
  };

  const openAttendanceModal = async (t: Training) => {
    setSelectedTraining(t);
    // Pre-populate already-logged attendees
    const res = await authFetch(`${API}/dash/training/${t.id}/attendance`);
    if (res.ok) {
      const data: TrainingAttendee[] = await res.json();
      setSelectedAttendees(new Set(data.map(a => a.employeeId)));
    } else {
      setSelectedAttendees(new Set(t.attendees?.map(a => a.employeeId) ?? []));
    }
    setAttEmpSearch("");
    setIsAttendanceModalOpen(true);
  };

  const handleLogAttendance = async () => {
    if (!selectedTraining || selectedAttendees.size === 0) return;
    setLoggingAttendance(true);
    try {
      const res = await authFetch(`${API}/dash/training/${selectedTraining.id}/attendance`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ attendees: [...selectedAttendees].map(id => ({ employeeId: id, status: "Attended" })) }),
      });
      if (!res.ok) { alert("Failed to log attendance."); return; }
      setIsAttendanceModalOpen(false);
      fetchTrainings();
    } catch (e) { console.error(e); }
    finally { setLoggingAttendance(false); }
  };

  const filtered = trainings.filter(t => {
    const q = searchQuery.toLowerCase();
    return (
      (t.title.toLowerCase().includes(q) || t.instructor?.toLowerCase().includes(q)) &&
      (filterType === "All" || t.type === filterType)
    );
  });

  const stats = [
    { label: "Total Sessions", value: trainings.length, color: "text-gray-900", bg: "bg-white" },
    { label: "Safety",         value: trainings.filter(t => t.type === "Safety").length,      color: "text-red-700",     bg: "bg-red-50" },
    { label: "Orientation",    value: trainings.filter(t => t.type === "Orientation").length,  color: "text-blue-700",    bg: "bg-blue-50" },
    { label: "Skill Up",       value: trainings.filter(t => t.type === "Skill Up").length,     color: "text-emerald-700", bg: "bg-emerald-50" },
  ];

  const fmtDate = (d: string) => new Date(d).toLocaleDateString("en-PK", { day: "2-digit", month: "short", year: "numeric" });

  const INPUT = "w-full rounded-lg border border-gray-200 px-3 py-2 text-sm text-gray-900 focus:outline-none focus:ring-2 focus:ring-brand-600/30";

  return (
    <div className="space-y-6 pb-10">

      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold leading-7 text-gray-900 sm:text-3xl sm:tracking-tight">Worker Training</h1>
          <p className="mt-1 text-sm text-gray-500">Skills development and safety certifications.</p>
        </div>
        <button
          onClick={() => setIsSlideOverOpen(true)}
          className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-brand-700 transition-colors"
        >
          <Plus className="h-4 w-4" /> Schedule Session
        </button>
      </div>

      {/* Stat Cards */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-4">
        {stats.map(s => (
          <motion.div key={s.label} initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }}
            className={cn("rounded-2xl border border-gray-100 shadow-sm px-5 py-4", s.bg)}
          >
            <p className="text-xs font-semibold text-gray-400 uppercase tracking-wider">{s.label}</p>
            <p className={cn("text-2xl font-extrabold mt-1", s.color)}>{s.value}</p>
          </motion.div>
        ))}
      </div>

      {/* Toolbar */}
      <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }}
        className="rounded-2xl bg-white shadow-sm border border-gray-100 overflow-hidden"
      >
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 px-6 py-4 border-b border-gray-100 bg-gray-50/40">
          <div className="relative max-w-xs w-full">
            <Search className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
            <input type="text" value={searchQuery} onChange={e => setSearchQuery(e.target.value)}
              placeholder="Search title or instructor…"
              className="w-full rounded-lg border border-gray-200 py-2 pl-9 pr-3 text-sm text-gray-900 placeholder:text-gray-400 focus:outline-none focus:ring-2 focus:ring-brand-600/30"
            />
          </div>
          <div className="flex items-center gap-1 flex-wrap">
            {["All", "Safety", "Orientation", "Skill Up"].map(t => (
              <button key={t} onClick={() => setFilterType(t)}
                className={cn(
                  "rounded-lg px-3 py-1.5 text-xs font-semibold transition-colors",
                  filterType === t ? "bg-brand-600 text-white" : "bg-gray-100 text-gray-600 hover:bg-gray-200"
                )}
              >{t}</button>
            ))}
          </div>
        </div>

        {/* Cards Grid */}
        {isLoading ? (
          <div className="flex items-center justify-center h-48 text-sm text-gray-400 animate-pulse">Loading sessions…</div>
        ) : filtered.length === 0 ? (
          <div className="flex flex-col items-center justify-center h-48 gap-3">
            <div className="h-12 w-12 rounded-full bg-gray-100 flex items-center justify-center">
              <GraduationCap className="h-6 w-6 text-gray-300" />
            </div>
            <p className="text-sm text-gray-400">No training sessions found.</p>
            <button onClick={() => setIsSlideOverOpen(true)} className="text-xs font-semibold text-brand-600 hover:underline">+ Schedule one</button>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5 p-6">
            {filtered.map(t => {
              const style = TYPE_STYLE[t.type] ?? TYPE_STYLE["Safety"];
              return (
                <motion.div key={t.id} initial={{ opacity: 0, y: 6 }} animate={{ opacity: 1, y: 0 }}
                  className={cn("bg-white rounded-2xl border shadow-sm flex flex-col justify-between hover:shadow-md transition-shadow", style.card)}
                >
                  <div className="p-5">
                    <div className="flex items-start justify-between gap-2 mb-3">
                      <span className={cn("inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-semibold ring-1 ring-inset", style.badge)}>
                        {t.type}
                      </span>
                      <button onClick={() => handleDelete(t.id)}
                        className="p-1 text-gray-300 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors"
                      >
                        <Trash2 className="h-3.5 w-3.5" />
                      </button>
                    </div>
                    <h3 className="text-base font-bold text-gray-900 leading-snug">{t.title}</h3>
                    {t.instructor && (
                      <p className="text-xs text-gray-400 mt-1">by {t.instructor}</p>
                    )}
                    <div className="mt-4 space-y-1.5">
                      <div className="flex items-center gap-2 text-xs text-gray-500">
                        <Calendar className="h-3.5 w-3.5 text-gray-400" />
                        {fmtDate(t.date)}
                      </div>
                      <div className="flex items-center gap-2 text-xs text-gray-500">
                        <Users className="h-3.5 w-3.5 text-gray-400" />
                        {t._count?.attendees ?? t.attendees?.length ?? 0} worker{(t._count?.attendees ?? 0) !== 1 ? "s" : ""} certified
                      </div>
                    </div>
                  </div>
                  <div className="px-5 pb-5">
                    <button
                      onClick={() => openAttendanceModal(t)}
                      className="w-full inline-flex items-center justify-center gap-2 rounded-xl py-2 text-xs font-semibold bg-gray-50 hover:bg-brand-50 hover:text-brand-600 text-gray-600 border border-gray-200 transition-colors"
                    >
                      <UserCheck className="h-3.5 w-3.5" /> Mark Attendance
                    </button>
                  </div>
                </motion.div>
              );
            })}
          </div>
        )}

        {filtered.length > 0 && (
          <div className="px-6 py-3 border-t border-gray-100 bg-gray-50/40">
            <p className="text-xs text-gray-400">{filtered.length} session{filtered.length !== 1 ? "s" : ""}</p>
          </div>
        )}
      </motion.div>

      {/* ── Schedule Slide-over ── */}
      <AnimatePresence>
        {isSlideOverOpen && (
          <>
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
              onClick={() => setIsSlideOverOpen(false)}
              className="fixed inset-0 bg-gray-900/40 backdrop-blur-sm z-40"
            />
            <motion.div initial={{ x: "100%" }} animate={{ x: 0 }} exit={{ x: "100%" }}
              transition={{ type: "spring", stiffness: 300, damping: 30 }}
              className="fixed inset-y-0 right-0 z-50 w-full max-w-sm bg-white shadow-2xl flex flex-col"
            >
              <div className="flex items-center justify-between px-6 py-5 border-b border-gray-100">
                <div className="flex items-center gap-2.5">
                  <div className="flex h-8 w-8 items-center justify-center rounded-lg bg-brand-50 text-brand-600">
                    <GraduationCap className="h-4 w-4" />
                  </div>
                  <h2 className="text-sm font-bold text-gray-900">Schedule Training</h2>
                </div>
                <button onClick={() => setIsSlideOverOpen(false)} className="text-gray-400 hover:text-gray-600">
                  <X className="h-5 w-5" />
                </button>
              </div>
              <div className="flex-1 overflow-y-auto px-6 py-6">
                <form id="train-form" onSubmit={handleCreate} className="space-y-5">
                  <div>
                    <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1.5">Session Title</label>
                    <input required type="text" value={formData.title}
                      onChange={e => setFormData(f => ({ ...f, title: e.target.value }))}
                      placeholder="e.g. Fire Safety Drill"
                      className={INPUT}
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1.5">Type</label>
                    <div className="grid grid-cols-3 gap-2">
                      {["Safety", "Orientation", "Skill Up"].map(t => (
                        <button type="button" key={t}
                          onClick={() => setFormData(f => ({ ...f, type: t }))}
                          className={cn(
                            "rounded-xl border-2 px-3 py-2 text-xs font-semibold text-center transition-colors",
                            formData.type === t ? "border-brand-600 bg-brand-50 text-brand-700" : "border-gray-200 text-gray-500 hover:border-gray-300"
                          )}
                        >{t}</button>
                      ))}
                    </div>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div>
                      <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1.5">Date</label>
                      <input required type="date" value={formData.date}
                        onChange={e => setFormData(f => ({ ...f, date: e.target.value }))}
                        className={INPUT}
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1.5">Instructor</label>
                      <input type="text" value={formData.instructor}
                        onChange={e => setFormData(f => ({ ...f, instructor: e.target.value }))}
                        placeholder="Name (optional)"
                        className={INPUT}
                      />
                    </div>
                  </div>
                </form>
              </div>
              <div className="px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3">
                <button type="button" onClick={() => setIsSlideOverOpen(false)}
                  className="rounded-lg px-4 py-2 text-sm font-semibold text-gray-600 hover:bg-gray-50 border border-gray-200 transition-colors"
                >Cancel</button>
                <button type="submit" form="train-form" disabled={saving}
                  className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-5 py-2 text-sm font-semibold text-white hover:bg-brand-700 transition-colors disabled:opacity-50"
                >Schedule</button>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>

      {/* ── Attendance Modal ── */}
      <AnimatePresence>
        {isAttendanceModalOpen && selectedTraining && (
          <>
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}
              onClick={() => setIsAttendanceModalOpen(false)}
              className="fixed inset-0 bg-gray-900/50 backdrop-blur-sm z-50"
            />
            <motion.div initial={{ opacity: 0, scale: 0.96, y: 12 }} animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.96, y: 12 }} transition={{ duration: 0.2 }}
              className="fixed inset-0 z-[60] flex items-center justify-center p-4 pointer-events-none"
            >
              <div className="bg-white rounded-2xl shadow-2xl border border-gray-200 w-full max-w-md pointer-events-auto">
                {/* Modal header */}
                <div className="flex items-start justify-between px-6 py-5 border-b border-gray-100">
                  <div>
                    <h2 className="text-sm font-bold text-gray-900">Mark Attendance</h2>
                    <p className="text-xs text-gray-400 mt-0.5">{selectedTraining.title}</p>
                  </div>
                  <button onClick={() => setIsAttendanceModalOpen(false)} className="text-gray-400 hover:text-gray-600">
                    <X className="h-5 w-5" />
                  </button>
                </div>

                <div className="px-6 py-5 space-y-4">
                  {/* Searchable multi-select */}
                  <div>
                    <label className="block text-xs font-semibold text-gray-500 uppercase tracking-wider mb-1.5">
                      Select Workers <span className="text-brand-600 normal-case font-normal">({selectedAttendees.size} selected)</span>
                    </label>
                    <div className="relative" ref={attDropRef}>
                      <div
                        onClick={() => setAttEmpDropOpen(o => !o)}
                        className={cn(
                          "flex items-center gap-2 w-full rounded-lg border px-3 py-2 bg-white cursor-pointer text-sm",
                          attEmpDropOpen ? "border-brand-600 ring-2 ring-brand-600/20" : "border-gray-200"
                        )}
                      >
                        <Search className="h-3.5 w-3.5 text-gray-400 flex-shrink-0" />
                        <input
                          type="text"
                          value={attEmpSearch}
                          onChange={e => { setAttEmpSearch(e.target.value); setAttEmpDropOpen(true); }}
                          onClick={e => { e.stopPropagation(); setAttEmpDropOpen(true); }}
                          placeholder="Search employees…"
                          className="flex-1 bg-transparent outline-none text-gray-900 placeholder:text-gray-400 text-sm"
                        />
                        <ChevronDown className={cn("h-3.5 w-3.5 text-gray-400 flex-shrink-0 transition-transform", attEmpDropOpen && "rotate-180")} />
                      </div>
                      {attEmpDropOpen && (
                        <div className="absolute z-10 mt-1 w-full rounded-xl border border-gray-200 bg-white shadow-lg max-h-48 overflow-y-auto">
                          {employees
                            .filter(e => {
                              const q = attEmpSearch.toLowerCase();
                              return !q || `${e.firstName} ${e.lastName}`.toLowerCase().includes(q) || (e.employeeId ?? "").toLowerCase().includes(q);
                            })
                            .map(emp => {
                              const checked = selectedAttendees.has(emp.id);
                              return (
                                <button type="button" key={emp.id}
                                  onClick={() => {
                                    setSelectedAttendees(prev => {
                                      const next = new Set(prev);
                                      if (checked) next.delete(emp.id); else next.add(emp.id);
                                      return next;
                                    });
                                  }}
                                  className={cn("w-full flex items-center gap-3 px-3 py-2.5 text-left hover:bg-gray-50 transition-colors", checked && "bg-brand-50")}
                                >
                                  <div className={cn(
                                    "h-4 w-4 rounded border flex-shrink-0 flex items-center justify-center transition-colors",
                                    checked ? "bg-brand-600 border-brand-600" : "border-gray-300"
                                  )}>
                                    {checked && <CheckCircle className="h-3 w-3 text-white" />}
                                  </div>
                                  <div className="h-7 w-7 flex-shrink-0 rounded-full bg-brand-100 flex items-center justify-center text-brand-700 text-xs font-bold uppercase">
                                    {emp.firstName.charAt(0)}{emp.lastName.charAt(0)}
                                  </div>
                                  <div>
                                    <p className="text-sm font-semibold text-gray-900">{emp.firstName} {emp.lastName}</p>
                                    <p className="text-xs text-gray-400 font-mono">#{emp.employeeId}</p>
                                  </div>
                                </button>
                              );
                            })}
                          {employees.filter(e => { const q = attEmpSearch.toLowerCase(); return !q || `${e.firstName} ${e.lastName}`.toLowerCase().includes(q); }).length === 0 && (
                            <p className="px-3 py-4 text-sm text-gray-400 text-center">No employees found</p>
                          )}
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Selected chips */}
                  {selectedAttendees.size > 0 && (
                    <div className="flex flex-wrap gap-1.5 max-h-24 overflow-y-auto">
                      {[...selectedAttendees].map(id => {
                        const emp = employees.find(e => e.id === id);
                        if (!emp) return null;
                        return (
                          <span key={id} className="inline-flex items-center gap-1 rounded-full bg-brand-50 px-2.5 py-1 text-xs font-semibold text-brand-700">
                            {emp.firstName} {emp.lastName}
                            <button type="button" onClick={() => setSelectedAttendees(prev => { const n = new Set(prev); n.delete(id); return n; })}
                              className="ml-0.5 text-brand-400 hover:text-brand-700"
                            ><X className="h-3 w-3" /></button>
                          </span>
                        );
                      })}
                    </div>
                  )}
                </div>

                <div className="px-6 py-4 border-t border-gray-100 flex items-center justify-between">
                  <button type="button" onClick={() => setIsAttendanceModalOpen(false)}
                    className="rounded-lg px-4 py-2 text-sm font-semibold text-gray-600 hover:bg-gray-50 border border-gray-200 transition-colors"
                  >Cancel</button>
                  <button
                    onClick={handleLogAttendance}
                    disabled={loggingAttendance || selectedAttendees.size === 0}
                    className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-5 py-2 text-sm font-semibold text-white hover:bg-brand-700 transition-colors disabled:opacity-50"
                  >
                    <CheckCircle className="h-4 w-4" />
                    {loggingAttendance ? "Saving…" : `Confirm (${selectedAttendees.size})`}
                  </button>
                </div>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}




