"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  Clock,
  Lock,
  Unlock,
  CheckCircle2,
  AlertTriangle,
  ShieldCheck,
  FileSpreadsheet,
  AlertCircle,
  Sparkles,
  ArrowRight,
  Filter,
  Search,
  Check,
  X,
  History,
} from "lucide-react";
import { toast } from "sonner";

interface RecentEditableSession {
  id: string;
  code: string;
  name: string;
  date: string;
  time: string;
  batch: string;
  semester: string;
  type: "PRACTICAL" | "THEORY";
  conductedHours: number;
  presentCount: number;
  totalStudents: number;
  status: "OPEN_EDIT" | "LOCKED";
  hoursRemaining: number;
  lockedAt?: string;
  attendanceUnits: number;
}

const initialEditableSessions: RecentEditableSession[] = [
  {
    id: "session_1042",
    code: "BHM201",
    name: "Food Production Operations Practical",
    date: "13-Oct-2026 (Today)",
    time: "09:00 AM - 01:00 PM",
    batch: "Batch B1",
    semester: "Sem III",
    type: "PRACTICAL",
    conductedHours: 4.0,
    presentCount: 28,
    totalStudents: 30,
    status: "OPEN_EDIT",
    hoursRemaining: 20,
    attendanceUnits: 4.0,
  },
  {
    id: "session_1038",
    code: "BHM201",
    name: "Classical Stocks, Glazes & Liaison Practical",
    date: "12-Oct-2026 (Yesterday)",
    time: "09:00 AM - 01:00 PM",
    batch: "Batch B1",
    semester: "Sem III",
    type: "PRACTICAL",
    conductedHours: 4.0,
    presentCount: 29,
    totalStudents: 30,
    status: "OPEN_EDIT",
    hoursRemaining: 6,
    attendanceUnits: 4.0,
  },
  {
    id: "session_1035",
    code: "BHM202",
    name: "Beverage Service Protocol Theory",
    date: "11-Oct-2026",
    time: "02:00 PM - 03:00 PM",
    batch: "Semester III",
    semester: "Sem III",
    type: "THEORY",
    conductedHours: 1.0,
    presentCount: 61,
    totalStudents: 65,
    status: "LOCKED",
    hoursRemaining: 0,
    lockedAt: "11-Oct-2026 15:45",
    attendanceUnits: 1.0,
  },
  {
    id: "session_1030",
    code: "BHM203",
    name: "Bakery & Viennoiserie Practice",
    date: "09-Oct-2026",
    time: "09:00 AM - 01:00 PM",
    batch: "Batch B2",
    semester: "Sem III",
    type: "PRACTICAL",
    conductedHours: 4.0,
    presentCount: 27,
    totalStudents: 28,
    status: "LOCKED",
    hoursRemaining: 0,
    lockedAt: "09-Oct-2026 14:10",
    attendanceUnits: 4.0,
  },
  {
    id: "session_1025",
    code: "BHM301",
    name: "Quantity Food Costing & Purchasing Theory",
    date: "08-Oct-2026",
    time: "02:00 PM - 03:00 PM",
    batch: "Semester V",
    semester: "Sem V",
    type: "THEORY",
    conductedHours: 1.0,
    presentCount: 29,
    totalStudents: 31,
    status: "LOCKED",
    hoursRemaining: 0,
    lockedAt: "08-Oct-2026 15:30",
    attendanceUnits: 1.0,
  },
];

export default function AuthorizedUpdatesPage() {
  const [sessions, setSessions] = useState<RecentEditableSession[]>(initialEditableSessions);
  const [showLockModal, setShowLockModal] = useState(false);
  const [sessionToLock, setSessionToLock] = useState<RecentEditableSession | null>(null);

  const [showUnlockModal, setShowUnlockModal] = useState(false);
  const [sessionToUnlock, setSessionToUnlock] = useState<RecentEditableSession | null>(null);
  const [unlockReason, setUnlockReason] = useState("");

  const handleConfirmLock = (sessionId: string) => {
    setSessions((prev) =>
      prev.map((s) =>
        s.id === sessionId
          ? {
              ...s,
              status: "LOCKED",
              hoursRemaining: 0,
              lockedAt: new Date().toLocaleDateString("en-GB") + " " + new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
            }
          : s
      )
    );
    setShowLockModal(false);
    toast.success(`Session ${sessionToLock?.code} successfully finalized and locked into institutional registers.`);
  };

  const handleRequestUnlock = () => {
    if (!unlockReason.trim()) {
      toast.error("Please provide a reason for the unlock request.");
      return;
    }
    toast.success(`Unlock request for ${sessionToUnlock?.code} (${sessionToUnlock?.date}) submitted to HOD & Academic Cell.`);
    setShowUnlockModal(false);
    setUnlockReason("");
  };

  return (
    <div className="space-y-6 pb-14 font-sans bg-[#F8FAFC]">
      {/* 1. Header & Breadcrumb */}
      <div>
        <div className="flex items-center gap-2 text-xs text-[#64748B] mb-2 font-medium">
          <Link href="/faculty/dashboard" className="hover:text-[#1769E8] transition-colors">
            Faculty Console
          </Link>
          <span>&gt;</span>
          <span>My Classes &amp; Attendance</span>
          <span>&gt;</span>
          <span className="text-[#071A4D] font-semibold">Authorized Updates &amp; Lock</span>
        </div>

        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <div className="flex items-center gap-2.5">
              <h1 className="text-3xl font-bold font-heading text-[#071A4D] tracking-tight">
                Authorized Updates &amp; Session Lock
              </h1>
              <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold bg-amber-50 text-amber-700 border border-amber-200">
                24h Grace Window Active
              </span>
            </div>
            <p className="text-[14px] text-[#64748B] mt-1 font-normal">
              Review recent attendance logs, make authorized corrections within the 24-hour timeframe, or commit final tamper-proof locks.
            </p>
          </div>

          <div className="flex items-center gap-2.5">
            <Link
              href="/faculty/classes/today"
              className="px-4 py-2 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-xs font-semibold flex items-center gap-2 shadow-xs transition-colors"
            >
              <CheckCircle2 className="w-3.5 h-3.5" />
              <span>Record Today's Attendance</span>
            </Link>
          </div>
        </div>
      </div>

      {/* 2. Policy Banner */}
      <div className="p-4 rounded-xl border border-blue-200 bg-blue-50/70 text-blue-950 text-xs flex items-start gap-3 shadow-2xs">
        <ShieldCheck className="w-5 h-5 text-[#1769E8] shrink-0 mt-0.5" />
        <div className="space-y-0.5">
          <p className="font-bold text-sm text-[#071A4D]">
            NCHMCT Authorized Attendance Revision Policy (Rule 14-B)
          </p>
          <p className="text-[#334155] leading-relaxed">
            Faculty instructors have an authorized <strong>24-hour grace window</strong> following the conclusion of any theory or practical session to modify attendance registers (e.g., verifying late medical slips or biometric discrepancies). Once finalized or expired, records are cryptographically sealed, and adjustments require formal HOD authorization.
          </p>
        </div>
      </div>

      {/* 3. Main Table Card */}
      <div className="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">
            <Clock className="w-5 h-5 text-amber-600" />
            <h2 className="font-heading font-bold text-lg text-[#071A4D]">
              Recent Sessions ({sessions.length})
            </h2>
          </div>
          <span className="text-xs text-[#64748B]">
            Showing sessions from the last 7 calendar days
          </span>
        </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 font-bold text-[#071A4D]">Session Details</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Conducted Date</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Cohort Batch</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Attendance Tally</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Status &amp; Time Window</th>
                <th className="py-3 px-4 font-bold text-[#071A4D] text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#E5EAF0]">
              {sessions.map((session) => (
                <tr key={session.id} className="hover:bg-[#F8FAFC] transition-colors">
                  <td className="py-3.5 px-3.5">
                    <div className="flex items-center gap-2">
                      <span className="font-mono font-bold text-[10px] bg-[#F1F6FC] text-[#1769E8] px-1.5 py-0.5 rounded border border-[#D0E2FF]">
                        {session.code}
                      </span>
                      <span className="font-bold text-[#071A4D] text-xs">
                        {session.name}
                      </span>
                    </div>
                    <div className="text-[11px] text-[#64748B] mt-0.5">
                      {session.time} • {session.type} ({session.attendanceUnits} Contact Units)
                    </div>
                  </td>
                  <td className="py-3.5 px-3.5 font-semibold text-[#071A4D]">
                    {session.date}
                  </td>
                  <td className="py-3.5 px-3.5 font-medium text-[#334155]">
                    {session.batch} ({session.semester})
                  </td>
                  <td className="py-3.5 px-3.5 text-center font-mono font-bold text-[#071A4D]">
                    {session.presentCount} / {session.totalStudents} ({((session.presentCount / session.totalStudents) * 100).toFixed(0)}%)
                  </td>
                  <td className="py-3.5 px-3.5 text-center">
                    {session.status === "OPEN_EDIT" ? (
                      <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-amber-50 text-amber-800 border border-amber-200">
                        <Clock className="w-3 h-3 text-amber-600" />
                        Editable ({session.hoursRemaining}h remaining)
                      </span>
                    ) : (
                      <div className="inline-flex flex-col items-center">
                        <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[10px] font-bold bg-[#DCFCE7] text-[#15803D] border border-[#BBF7D0]">
                          <Lock className="w-3 h-3 text-emerald-600" />
                          Finalized &amp; Locked
                        </span>
                        {session.lockedAt && (
                          <span className="text-[9px] text-slate-400 font-mono mt-0.5">
                            Sealed: {session.lockedAt}
                          </span>
                        )}
                      </div>
                    )}
                  </td>
                  <td className="py-3.5 px-4 text-right">
                    <div className="flex items-center justify-end gap-2">
                      {session.status === "OPEN_EDIT" ? (
                        <>
                          <Link
                            href={`/faculty/classes/${session.id}/mark`}
                            className="px-2.5 py-1.5 rounded bg-white border border-[#E2E8F0] hover:bg-slate-50 text-[#1769E8] font-semibold text-xs transition-colors shadow-2xs"
                          >
                            Update Marks
                          </Link>
                          <button
                            onClick={() => {
                              setSessionToLock(session);
                              setShowLockModal(true);
                            }}
                            className="px-2.5 py-1.5 rounded bg-emerald-600 hover:bg-emerald-700 text-white font-semibold text-xs transition-colors shadow-2xs flex items-center gap-1"
                          >
                            <Lock className="w-3 h-3" />
                            <span>Finalize &amp; Lock</span>
                          </button>
                        </>
                      ) : (
                        <div className="flex items-center gap-1.5">
                          <Link
                            href={`/faculty/classes/${session.id}/review`}
                            className="px-2.5 py-1.5 rounded bg-slate-50 border border-slate-200 text-slate-700 hover:bg-slate-100 font-semibold text-xs transition-colors"
                          >
                            View Summary
                          </Link>
                          <button
                            onClick={() => {
                              setSessionToUnlock(session);
                              setShowUnlockModal(true);
                            }}
                            className="px-2 py-1.5 rounded border border-slate-200 hover:bg-amber-50 hover:border-amber-200 text-slate-500 hover:text-amber-800 font-semibold text-[11px] transition-colors"
                          >
                            Request Unlock
                          </button>
                        </div>
                      )}
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* 4. Finalize & Lock Modal */}
      {showLockModal && sessionToLock && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-2xs p-4">
          <div className="bg-white rounded-2xl border border-slate-200 shadow-xl w-full max-w-md p-6 space-y-4 animate-in fade-in zoom-in-95 duration-150">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-emerald-50 border border-emerald-200 text-emerald-600 flex items-center justify-center shrink-0">
                <Lock className="w-5 h-5" />
              </div>
              <div>
                <h3 className="font-heading font-bold text-base text-[#071A4D]">
                  Finalize &amp; Lock Attendance Session?
                </h3>
                <p className="text-xs text-slate-500">
                  {sessionToLock.code} • {sessionToLock.name} ({sessionToLock.date})
                </p>
              </div>
            </div>

            <div className="p-3 bg-amber-50 rounded-xl border border-amber-200 text-xs text-amber-900 space-y-1">
              <p className="font-bold flex items-center gap-1">
                <AlertTriangle className="w-4 h-4 text-amber-600 shrink-0" />
                Permanent Record Commitment Notice
              </p>
              <p className="text-amber-800 leading-relaxed">
                Finalizing will immediately lock attendance records for <strong>{sessionToLock.totalStudents} students</strong> ({sessionToLock.presentCount} Present). Once locked, subsequent modifications will require administrative authorization.
              </p>
            </div>

            <div className="flex items-center justify-end gap-2 pt-2">
              <button
                onClick={() => setShowLockModal(false)}
                className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-xs font-semibold hover:bg-slate-50 transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={() => handleConfirmLock(sessionToLock.id)}
                className="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-semibold transition-colors flex items-center gap-1.5 shadow-2xs"
              >
                <Lock className="w-3.5 h-3.5" />
                <span>Confirm &amp; Lock Session</span>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 5. Request Unlock Modal */}
      {showUnlockModal && sessionToUnlock && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-2xs p-4">
          <div className="bg-white rounded-2xl border border-slate-200 shadow-xl w-full max-w-md p-6 space-y-4 animate-in fade-in zoom-in-95 duration-150">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-blue-50 border border-blue-200 text-[#1769E8] flex items-center justify-center shrink-0">
                <Unlock className="w-5 h-5" />
              </div>
              <div>
                <h3 className="font-heading font-bold text-base text-[#071A4D]">
                  Request Administrative Unlock
                </h3>
                <p className="text-xs text-slate-500">
                  {sessionToUnlock.code} • {sessionToUnlock.date}
                </p>
              </div>
            </div>

            <p className="text-xs text-[#64748B]">
              Submit a formal request to Academic Cell to unlock this session for attendance correction.
            </p>

            <div>
              <label className="text-xs font-semibold text-[#071A4D] block mb-1">
                Reason for Revision Request:
              </label>
              <textarea
                rows={3}
                value={unlockReason}
                onChange={(e) => setUnlockReason(e.target.value)}
                placeholder="e.g., Sanctioned medical leave certificate presented by student..."
                className="w-full p-2.5 text-xs bg-slate-50 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#1769E8] focus:bg-white transition-colors"
              />
            </div>

            <div className="flex items-center justify-end gap-2 pt-2">
              <button
                onClick={() => setShowUnlockModal(false)}
                className="px-4 py-2 border border-slate-200 text-slate-600 rounded-lg text-xs font-semibold hover:bg-slate-50 transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleRequestUnlock}
                className="px-4 py-2 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-xs font-semibold transition-colors flex items-center gap-1.5 shadow-2xs"
              >
                <span>Submit Request to HOD</span>
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
