"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  Search,
  RotateCcw,
  Plus,
  Eye,
  Trash2,
  ChevronLeft,
  ChevronRight,
  FileSpreadsheet,
  FileText,
  CalendarDays,
  Play,
  RotateCw,
  Sparkles,
  Clock,
  CheckCircle2,
  Lock,
} from "lucide-react";
import { toast } from "sonner";

interface DisplaySession {
  id: string;
  sessionDate: string;
  scheduledTime: string;
  subjectCode: string;
  subjectName: string;
  batchName: string;
  roomName: string;
  facultyName: string;
  hours: number;
  status: "Scheduled" | "Conducted" | "Locked" | "Holiday";
}

const initialSessions: DisplaySession[] = [
  {
    id: "sess-gen-101",
    sessionDate: "2026-10-07",
    scheduledTime: "09:00 – 13:00",
    subjectCode: "BHM201",
    subjectName: "Food Production Operations Practical",
    batchName: "Batch B1",
    roomName: "Basic Training Kitchen B",
    facultyName: "Chef Rajesh Sharma",
    hours: 4.0,
    status: "Scheduled",
  },
  {
    id: "sess-gen-102",
    sessionDate: "2026-10-07",
    scheduledTime: "09:00 – 13:00",
    subjectCode: "BHM203",
    subjectName: "Bakery & Confectionery Practical",
    batchName: "Batch B2",
    roomName: "Bakery Lab BAK-1",
    facultyName: "Chef Vikram Singh",
    hours: 4.0,
    status: "Scheduled",
  },
  {
    id: "sess-gen-103",
    sessionDate: "2026-10-07",
    scheduledTime: "14:00 – 15:00",
    subjectCode: "BHM202",
    subjectName: "Food & Beverage Service Theory",
    batchName: "Semester III Cohort",
    roomName: "Lecture Hall 101",
    facultyName: "Prof. Ananya Sen",
    hours: 1.0,
    status: "Scheduled",
  },
  {
    id: "sess-gen-104",
    sessionDate: "2026-10-06",
    scheduledTime: "09:00 – 13:00",
    subjectCode: "BHM201",
    subjectName: "Food Production Operations Practical",
    batchName: "Batch B1",
    roomName: "Basic Training Kitchen B",
    facultyName: "Chef Rajesh Sharma",
    hours: 4.0,
    status: "Locked",
  },
  {
    id: "sess-gen-105",
    sessionDate: "2026-10-02",
    scheduledTime: "09:00 – 13:00",
    subjectCode: "BHM201",
    subjectName: "Food Production Operations Practical",
    batchName: "Batch B1",
    roomName: "Basic Training Kitchen B",
    facultyName: "Chef Rajesh Sharma",
    hours: 4.0,
    status: "Holiday",
  },
];

export default function SessionGeneratorPage() {
  const [sessions, setSessions] = useState<DisplaySession[]>(initialSessions);
  const [selectedStatus, setSelectedStatus] = useState("All Status");
  const [selectedDate, setSelectedDate] = useState("All Dates");
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedRows, setSelectedRows] = useState<string[]>([]);
  const [pageSize, setPageSize] = useState("10");

  // Generator form state
  const [startDate, setStartDate] = useState("2026-10-08");
  const [endDate, setEndDate] = useState("2026-10-15");
  const [semesterFilter, setSemesterFilter] = useState("Semester III");
  const [skipHolidays, setSkipHolidays] = useState(true);

  const filteredSessions = sessions.filter((s) => {
    const matchesStatus =
      selectedStatus === "All Status" || s.status === selectedStatus;
    const matchesDate =
      selectedDate === "All Dates" || s.sessionDate === selectedDate;
    const matchesSearch =
      searchQuery === "" ||
      s.subjectCode.toLowerCase().includes(searchQuery.toLowerCase()) ||
      s.subjectName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      s.facultyName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      s.roomName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      s.sessionDate.includes(searchQuery);
    return matchesStatus && matchesDate && matchesSearch;
  });

  const handleSelectAll = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.checked) {
      setSelectedRows(filteredSessions.map((s) => s.id));
    } else {
      setSelectedRows([]);
    }
  };

  const handleRowSelect = (id: string) => {
    setSelectedRows((prev) =>
      prev.includes(id) ? prev.filter((r) => r !== id) : [...prev, id]
    );
  };

  const handleResetFilters = () => {
    setSelectedStatus("All Status");
    setSelectedDate("All Dates");
    setSearchQuery("");
    toast.info("Filters reset to default");
  };

  const handleRunGenerator = (e: React.FormEvent) => {
    e.preventDefault();
    const newSession: DisplaySession = {
      id: `sess-gen-${Date.now()}`,
      sessionDate: startDate,
      scheduledTime: "09:00 – 13:00",
      subjectCode: "BHM201",
      subjectName: "Food Production Operations Practical",
      batchName: "Batch B1",
      roomName: "Basic Training Kitchen B",
      facultyName: "Chef Rajesh Sharma",
      hours: 4.0,
      status: "Scheduled",
    };
    setSessions((prev) => [newSession, ...prev]);
    toast.success(`Generated 8 timetable attendance registers for ${startDate} to ${endDate}`);
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case "Scheduled":
        return "bg-[#E0F2FE] text-[#0369A1] border-[#BAE6FD]";
      case "Conducted":
        return "bg-[#DCFCE7] text-[#15803D] border-[#BBF7D0]";
      case "Locked":
        return "bg-[#F3E8FF] text-[#7E22CE] border-[#E9D5FF]";
      case "Holiday":
        return "bg-[#FEF3C7] text-[#B45309] border-[#FDE68A]";
      default:
        return "bg-slate-100 text-slate-700 border-slate-200";
    }
  };

  return (
    <div className="space-y-6 pb-12 font-sans bg-[#F8FAFC] min-h-screen">
      {/* 1. Header Bar */}
      <div>
        <div className="flex items-center gap-2 text-xs text-[#64748B] mb-2 font-medium">
          <Link href="/admin/dashboard" className="hover:text-[#1769E8] transition-colors">
            Home
          </Link>
          <span>&gt;</span>
          <Link href="/admin/sessions/generator" className="hover:text-[#1769E8] transition-colors">
            Attendance System
          </Link>
          <span>&gt;</span>
          <span className="text-[#071A4D] font-semibold">Session Generator</span>
        </div>

        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <h1 className="text-3xl font-bold font-heading text-[#071A4D] tracking-tight">
              Attendance Session Generator
            </h1>
            <p className="text-[15px] text-[#64748B] mt-1 font-normal">
              Instantiate daily classroom and commercial kitchen practical timetable sessions into active attendance registers.
            </p>
          </div>

          <div className="flex items-center gap-3">
            <button
              onClick={() => toast.success("Exporting session schedule to Excel...")}
              className="px-4 py-2 bg-white border border-[#E2E8F0] rounded-lg text-sm font-medium text-[#334155] hover:bg-slate-50 transition-colors flex items-center gap-2 shadow-xs cursor-pointer"
            >
              <FileSpreadsheet className="w-4 h-4 text-emerald-600" />
              <span>Export</span>
            </button>
            <button
              onClick={() => toast.info("Generating session turnout report...")}
              className="px-4 py-2 bg-white border border-[#E2E8F0] rounded-lg text-sm font-medium text-[#334155] hover:bg-slate-50 transition-colors flex items-center gap-2 shadow-xs cursor-pointer"
            >
              <FileText className="w-4 h-4 text-purple-600" />
              <span>Generate Report</span>
            </button>
            <button
              onClick={() => {
                toast.success("Successfully generated 6 timetable sessions for today.");
              }}
              className="px-5 py-2.5 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-sm font-semibold transition-colors flex items-center gap-2 shadow-sm cursor-pointer"
            >
              <Play className="w-4 h-4" />
              <span>+ Generate Today's Register</span>
            </button>
          </div>
        </div>
      </div>

      {/* 2. Filter Bar */}
      <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs p-4">
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-12 gap-3.5 items-end">
          <div className="lg:col-span-3">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Session Status
            </label>
            <select
              value={selectedStatus}
              onChange={(e) => setSelectedStatus(e.target.value)}
              className="w-full bg-white border border-[#E2E8F0] text-sm text-[#0F172A] rounded-lg px-3 py-2 font-medium focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer"
            >
              <option>All Status</option>
              <option>Scheduled</option>
              <option>Conducted</option>
              <option>Locked</option>
              <option>Holiday</option>
            </select>
          </div>

          <div className="lg:col-span-7">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Search
            </label>
            <div className="relative">
              <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-[#94A3B8]" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search subject code, instructor, room, or date (YYYY-MM-DD)..."
                className="w-full pl-9 pr-3 py-2 bg-white border border-[#E2E8F0] text-sm text-[#0F172A] placeholder:text-[#94A3B8] rounded-lg focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all"
              />
            </div>
          </div>

          <div className="lg:col-span-2 flex items-center gap-2">
            <button
              onClick={() => toast.success(`Found ${filteredSessions.length} sessions`)}
              className="flex-1 bg-[#1769E8] hover:bg-[#1255be] text-white py-2 rounded-lg text-sm font-semibold transition-colors flex items-center justify-center gap-1.5 shadow-xs cursor-pointer"
            >
              <Search className="w-4 h-4" />
              <span>Search</span>
            </button>
            <button
              onClick={handleResetFilters}
              className="border border-[#E2E8F0] hover:bg-slate-50 text-[#64748B] p-2 rounded-lg text-sm font-medium transition-colors flex items-center justify-center cursor-pointer"
              title="Reset Filters"
            >
              <RotateCcw className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      {/* 3. Main Split Layout */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
        {/* Left (8 cols): Table */}
        <div className="lg:col-span-8 bg-white rounded-xl border border-[#E5EAF0] shadow-xs overflow-hidden">
          <div className="p-4 border-b border-[#E5EAF0] flex items-center justify-between">
            <div className="flex items-center gap-2.5">
              <CalendarDays className="w-5 h-5 text-[#1769E8]" />
              <h2 className="font-heading font-bold text-lg text-[#071A4D]">
                Instantiated Sessions ({filteredSessions.length})
              </h2>
            </div>
            <div className="flex items-center gap-2">
              <select
                value={pageSize}
                onChange={(e) => setPageSize(e.target.value)}
                className="text-xs bg-white border border-[#E2E8F0] rounded-lg px-2.5 py-1.5 font-medium text-[#475569] outline-none cursor-pointer"
              >
                <option value="10">10 per page</option>
                <option value="25">25 per page</option>
              </select>
            </div>
          </div>

          <div className="overflow-x-auto">
            <table className="w-full text-left text-xs border-collapse">
              <thead>
                <tr className="bg-[#F8FAFC] border-b border-[#E5EAF0] text-[#64748B] font-semibold">
                  <th className="py-3 px-3.5 w-10 text-center">
                    <input
                      type="checkbox"
                      checked={
                        selectedRows.length === filteredSessions.length &&
                        filteredSessions.length > 0
                      }
                      onChange={handleSelectAll}
                      className="rounded border-[#CBD5E1] text-[#1769E8] focus:ring-0 cursor-pointer"
                    />
                  </th>
                  <th className="py-3 px-2 w-8 text-center text-[#64748B]">#</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D]">Date &amp; Time</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D]">Subject &amp; Code</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D]">Batch &amp; Facility</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D]">Instructor</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Hours</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Status</th>
                  <th className="py-3 px-4 font-bold text-[#071A4D] text-right">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-[#E5EAF0]">
                {filteredSessions.length === 0 ? (
                  <tr>
                    <td colSpan={9} className="py-12 text-center text-slate-400">
                      No instantiated sessions found.
                    </td>
                  </tr>
                ) : (
                  filteredSessions.map((s, idx) => (
                    <tr
                      key={s.id}
                      className={`hover:bg-[#F8FAFC] transition-colors ${
                        selectedRows.includes(s.id) ? "bg-[#EFF6FF]/40" : ""
                      }`}
                    >
                      <td className="py-3.5 px-3.5 text-center">
                        <input
                          type="checkbox"
                          checked={selectedRows.includes(s.id)}
                          onChange={() => handleRowSelect(s.id)}
                          className="rounded border-[#CBD5E1] text-[#1769E8] focus:ring-0 cursor-pointer"
                        />
                      </td>
                      <td className="py-3.5 px-2 text-center text-[#94A3B8] font-medium">
                        {idx + 1}
                      </td>
                      <td className="py-3.5 px-3.5">
                        <div className="font-mono font-bold text-xs text-[#071A4D]">
                          {s.sessionDate}
                        </div>
                        <div className="text-[11px] text-[#64748B]">
                          {s.scheduledTime}
                        </div>
                      </td>
                      <td className="py-3.5 px-3.5">
                        <span className="font-mono font-bold text-xs bg-[#F1F6FC] text-[#1769E8] px-2 py-0.5 rounded border border-[#D0E2FF] mr-1.5">
                          {s.subjectCode}
                        </span>
                        <div className="font-semibold text-[#334155] text-xs mt-1">
                          {s.subjectName}
                        </div>
                      </td>
                      <td className="py-3.5 px-3.5">
                        <div className="font-medium text-[#071A4D]">{s.batchName}</div>
                        <div className="text-[11px] text-[#64748B]">{s.roomName}</div>
                      </td>
                      <td className="py-3.5 px-3.5 font-medium text-[#334155]">
                        {s.facultyName}
                      </td>
                      <td className="py-3.5 px-3.5 text-center font-mono font-bold text-[#071A4D]">
                        {s.hours.toFixed(1)}h
                      </td>
                      <td className="py-3.5 px-3.5 text-center">
                        <span
                          className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-[11px] font-bold border ${getStatusBadge(
                            s.status
                          )}`}
                        >
                          {s.status}
                        </span>
                      </td>
                      <td className="py-3.5 px-4 text-right">
                        <div className="flex items-center justify-end gap-1.5">
                          <button
                            onClick={() =>
                              toast.info(`Viewing attendance register for ${s.subjectCode}`)
                            }
                            className="p-1.5 text-[#64748B] hover:text-[#1769E8] hover:bg-[#EFF6FF] rounded-md transition-colors cursor-pointer"
                            title="View Session"
                          >
                            <Eye className="w-3.5 h-3.5" />
                          </button>
                          <button
                            onClick={() => toast.success(`Regenerated register for ${s.subjectCode}`)}
                            className="p-1.5 text-[#64748B] hover:text-[#1769E8] hover:bg-[#EFF6FF] rounded-md transition-colors cursor-pointer"
                            title="Regenerate"
                          >
                            <RotateCw className="w-3.5 h-3.5" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  ))
                )}
              </tbody>
            </table>
          </div>

          <div className="p-4 border-t border-[#E5EAF0] flex flex-col sm:flex-row items-center justify-between gap-3 text-xs text-[#64748B]">
            <div>
              Showing 1 to {filteredSessions.length} of {sessions.length} sessions
            </div>
            <div className="flex items-center gap-1">
              <button className="p-1.5 border border-[#E2E8F0] rounded-md hover:bg-slate-50 transition-colors cursor-pointer">
                <ChevronLeft className="w-3.5 h-3.5" />
              </button>
              <button className="px-3 py-1 bg-[#1769E8] text-white font-bold rounded-md text-xs">
                1
              </button>
              <button className="p-1.5 border border-[#E2E8F0] rounded-md hover:bg-slate-50 transition-colors cursor-pointer">
                <ChevronRight className="w-3.5 h-3.5" />
              </button>
            </div>
          </div>
        </div>

        {/* Right (4 cols): Range Generator Form + Protocol */}
        <div className="lg:col-span-4 space-y-5">
          <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs p-5">
            <div className="flex items-center justify-between pb-3 mb-4 border-b border-[#E5EAF0]">
              <div className="flex items-center gap-2">
                <Play className="w-4 h-4 text-[#1769E8]" />
                <h3 className="font-heading font-bold text-base text-[#071A4D]">
                  Batch Range Generator
                </h3>
              </div>
            </div>

            <form onSubmit={handleRunGenerator} className="space-y-4 text-xs">
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block font-semibold text-[#334155] mb-1">
                    Start Date <span className="text-rose-500">*</span>
                  </label>
                  <input
                    type="date"
                    required
                    value={startDate}
                    onChange={(e) => setStartDate(e.target.value)}
                    className="w-full px-3 py-2 border border-[#E2E8F0] rounded-lg text-sm text-[#0F172A] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all font-mono"
                  />
                </div>

                <div>
                  <label className="block font-semibold text-[#334155] mb-1">
                    End Date <span className="text-rose-500">*</span>
                  </label>
                  <input
                    type="date"
                    required
                    value={endDate}
                    onChange={(e) => setEndDate(e.target.value)}
                    className="w-full px-3 py-2 border border-[#E2E8F0] rounded-lg text-sm text-[#0F172A] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all font-mono"
                  />
                </div>
              </div>

              <div>
                <label className="block font-semibold text-[#334155] mb-1">
                  Target Semester
                </label>
                <select
                  value={semesterFilter}
                  onChange={(e) => setSemesterFilter(e.target.value)}
                  className="w-full px-3 py-2 border border-[#E2E8F0] rounded-lg text-sm text-[#0F172A] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all bg-white cursor-pointer"
                >
                  <option>All Semesters</option>
                  <option>Semester I</option>
                  <option>Semester III</option>
                  <option>Semester V</option>
                </select>
              </div>

              <div className="flex items-center justify-between pt-1">
                <span className="font-semibold text-[#334155]">Skip Gazetted Holidays</span>
                <button
                  type="button"
                  onClick={() => setSkipHolidays(!skipHolidays)}
                  className={`w-11 h-6 flex items-center rounded-full p-1 transition-colors cursor-pointer ${
                    skipHolidays ? "bg-[#1769E8]" : "bg-slate-300"
                  }`}
                >
                  <div
                    className={`bg-white w-4 h-4 rounded-full shadow-md transform transition-transform ${
                      skipHolidays ? "translate-x-5" : "translate-x-0"
                    }`}
                  />
                </button>
              </div>

              <div className="pt-2">
                <button
                  type="submit"
                  className="w-full py-2.5 px-3 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-xs font-semibold transition-colors flex items-center justify-center gap-1.5 shadow-xs cursor-pointer"
                >
                  <Play className="w-3.5 h-3.5" />
                  <span>Run Session Instantiation</span>
                </button>
              </div>
            </form>
          </div>

          {/* Session Lifecycle Protocol Card */}
          <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs p-4 text-xs">
            <div className="flex items-center gap-2 font-bold text-[#071A4D] mb-2.5 pb-2 border-b border-[#E5EAF0]">
              <Sparkles className="w-4 h-4 text-amber-500" />
              <span>NCHMCT Session Lifecycle</span>
            </div>
            <div className="space-y-2 text-[#475569]">
              <div className="flex items-center justify-between">
                <span className="font-medium text-sky-700">Scheduled</span>
                <span className="font-mono font-bold text-sky-700">Instantiated from Timetable</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="font-medium text-emerald-700">Conducted</span>
                <span className="font-mono font-bold text-emerald-700">Marked by Faculty</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="font-medium text-purple-700">Locked</span>
                <span className="font-mono font-bold text-purple-700">Immutable for APR</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="font-medium text-amber-700">Holiday</span>
                <span className="font-mono font-bold text-amber-700">Zero Contact Hours</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
