"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  Search,
  RotateCcw,
  CheckCircle2,
  XCircle,
  Eye,
  FileCheck2,
  FileSpreadsheet,
  FileText,
  HeartPulse,
  Sliders,
  Award,
  RefreshCw,
  History,
  ShieldCheck,
  Clock,
  ChevronLeft,
  ChevronRight,
  UserCheck,
  AlertCircle,
} from "lucide-react";
import { toast } from "sonner";

interface ApprovalCase {
  id: string;
  appCode: string;
  rollNumber: string;
  studentName: string;
  batch: string;
  absencePeriod: string;
  durationHours: string;
  hoursNumber: number;
  diagnosis: string;
  cmoEndorsed: boolean;
  status: "Pending" | "Approved" | "Rejected";
  certRef: string;
}

const initialApprovalRows: ApprovalCase[] = [
  {
    id: "app-1",
    appCode: "MED-APP-201",
    rollNumber: "2441112003",
    studentName: "Chirag Banerjee",
    batch: "Sem-IV",
    absencePeriod: "01 Oct - 03 Oct 2026",
    durationHours: "3 Days (12 hrs)",
    hoursNumber: 12.0,
    diagnosis: "Acute Viral Gastroenteritis",
    cmoEndorsed: true,
    status: "Pending",
    certRef: "CERT-2026-103-HOSPITAL.pdf",
  },
  {
    id: "app-2",
    appCode: "MED-APP-202",
    rollNumber: "2441112005",
    studentName: "Farhan Ahmed",
    batch: "Sem-IV",
    absencePeriod: "20 Sep - 22 Sep 2026",
    durationHours: "2 Days (8 hrs)",
    hoursNumber: 8.0,
    diagnosis: "Impacted molar extraction",
    cmoEndorsed: true,
    status: "Approved",
    certRef: "CERT-2026-105-DENTAL.pdf",
  },
  {
    id: "app-3",
    appCode: "MED-APP-203",
    rollNumber: "2441112009",
    studentName: "Jayant Verma",
    batch: "Sem-VI",
    absencePeriod: "10 Sep - 18 Sep 2026",
    durationHours: "8 Days (32 hrs)",
    hoursNumber: 32.0,
    diagnosis: "Typhoid fever under antibiotic regimen",
    cmoEndorsed: false,
    status: "Pending",
    certRef: "CERT-2026-109-CLINIC.pdf",
  },
  {
    id: "app-4",
    appCode: "MED-APP-204",
    rollNumber: "2441112015",
    studentName: "Rohan Mukherjee",
    batch: "Sem-II",
    absencePeriod: "14 Aug - 16 Aug 2026",
    durationHours: "3 Days (10 hrs)",
    hoursNumber: 10.0,
    diagnosis: "Chronic fatigue syndrome",
    cmoEndorsed: false,
    status: "Rejected",
    certRef: "CERT-2026-115-PRIVATE.pdf",
  },
  {
    id: "app-5",
    appCode: "MED-APP-205",
    rollNumber: "2441112022",
    studentName: "Ananya Iyer",
    batch: "Sem-II",
    absencePeriod: "06 Oct - 10 Oct 2026",
    durationHours: "5 Days (10 hrs)",
    hoursNumber: 10.0,
    diagnosis: "Grade II Lateral Ankle Ligament Sprain",
    cmoEndorsed: true,
    status: "Pending",
    certRef: "CERT-2026-121-ORTHO.pdf",
  },
];

export default function MedicalApprovalsPage() {
  const [cases, setCases] = useState<ApprovalCase[]>(initialApprovalRows);
  const [searchQuery, setSearchQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState("All Status");
  const [selectedCase, setSelectedCase] = useState<ApprovalCase | null>(null);

  const filteredCases = cases.filter((c) => {
    const matchesStatus = statusFilter === "All Status" || c.status === statusFilter;
    const matchesSearch =
      searchQuery === "" ||
      c.studentName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      c.rollNumber.includes(searchQuery) ||
      c.appCode.toLowerCase().includes(searchQuery.toLowerCase()) ||
      c.diagnosis.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesStatus && matchesSearch;
  });

  const handleApprove = (id: string) => {
    setCases((prev) =>
      prev.map((c) => (c.id === id ? { ...c, status: "Approved" } : c))
    );
    if (selectedCase?.id === id) {
      setSelectedCase((prev) => (prev ? { ...prev, status: "Approved" } : null));
    }
    toast.success("Medical claim approved! Attendance hours scheduled for recalculation.");
  };

  const handleReject = (id: string) => {
    setCases((prev) =>
      prev.map((c) => (c.id === id ? { ...c, status: "Rejected" } : c))
    );
    if (selectedCase?.id === id) {
      setSelectedCase((prev) => (prev ? { ...prev, status: "Rejected" } : null));
    }
    toast.error("Medical claim rejected.");
  };

  const navTabs = [
    { label: "Requests", href: "/admin/adjustments/medical", icon: HeartPulse, active: false },
    { label: "Certificate Reference", href: "/admin/adjustments/medical/certificates", icon: FileCheck2, active: false },
    { label: "Approvals", href: "/admin/adjustments/medical/approvals", icon: CheckCircle2, active: true },
    { label: "Configurable %", href: "/admin/adjustments/medical/policy", icon: Sliders, active: false },
    { label: "Condonations", href: "/admin/adjustments/condonation", icon: FileText, active: false },
    { label: "Approved Hours", href: "/admin/adjustments/approved", icon: Award, active: false },
    { label: "Recalculation", href: "/admin/adjustments/recalculation", icon: RefreshCw, active: false },
    { label: "History", href: "/admin/adjustments/history", icon: History, active: false },
    { label: "Audit Trail", href: "/admin/adjustments/audit-trail", icon: ShieldCheck, active: false },
  ];

  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/adjustments/medical" className="hover:text-[#1769E8] transition-colors">
            Medical & Condonation
          </Link>
          <span>&gt;</span>
          <span className="text-[#071A4D] font-semibold">Medical Approvals Workflow</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">
              Medical Approvals Queue
            </h1>
            <p className="text-[15px] text-[#64748B] mt-1 font-normal">
              Official committee review and approval queue for submitted medical certificates with CMO verification and attendance adjustments.
            </p>
          </div>

          <div className="flex items-center gap-3">
            <button
              onClick={() => toast.success("Exporting approvals queue 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 Queue</span>
            </button>
          </div>
        </div>
      </div>

      {/* 2. Subcategory Navigation Tabs */}
      <div className="flex items-center gap-1.5 overflow-x-auto pb-1 border-b border-[#E2E8F0]">
        {navTabs.map((tab) => {
          const Icon = tab.icon;
          return (
            <Link
              key={tab.href}
              href={tab.href}
              className={`flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-semibold whitespace-nowrap transition-all ${
                tab.active
                  ? "bg-[#081A2E] text-white shadow-xs"
                  : "bg-white text-[#64748B] hover:text-[#071A4D] hover:bg-slate-100 border border-[#E2E8F0]"
              }`}
            >
              <Icon className="w-3.5 h-3.5" />
              <span>{tab.label}</span>
            </Link>
          );
        })}
      </div>

      {/* 3. Filter Bar */}
      <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs p-4">
        <div className="grid grid-cols-1 md:grid-cols-12 gap-3.5 items-end">
          <div className="md:col-span-3">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Review Status
            </label>
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(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>Pending</option>
              <option>Approved</option>
              <option>Rejected</option>
            </select>
          </div>

          <div className="md:col-span-7">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Search Cases
            </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 by student name, roll number, or application ID..."
                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="md:col-span-2 flex items-center gap-2">
            <button
              onClick={() => toast.success(`Found ${filteredCases.length} cases`)}
              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>Filter</span>
            </button>
            <button
              onClick={() => {
                setStatusFilter("All Status");
                setSearchQuery("");
                toast.info("Reset filters");
              }}
              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"
            >
              <RotateCcw className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      {/* 4. Table */}
      <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">
            <CheckCircle2 className="w-5 h-5 text-[#1769E8]" />
            <h2 className="font-heading font-bold text-lg text-[#071A4D]">
              Medical Decision Queue ({filteredCases.length})
            </h2>
          </div>
          <span className="text-xs text-[#64748B]">Two-Tier CMO & Academic Sign-Off</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 w-8 text-center">#</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">App Code</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Student Roll & Name</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Absence Window</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]">Clinical Diagnosis</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">CMO Endorsement</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Decision Status</th>
                <th className="py-3 px-4 font-bold text-[#071A4D] text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#E5EAF0]">
              {filteredCases.length === 0 ? (
                <tr>
                  <td colSpan={9} className="py-12 text-center text-slate-400">
                    No cases match filter criteria.
                  </td>
                </tr>
              ) : (
                filteredCases.map((c, idx) => (
                  <tr key={c.id} className="hover:bg-[#F8FAFC] transition-colors">
                    <td className="py-3.5 px-3.5 text-center text-[#94A3B8] font-medium">
                      {idx + 1}
                    </td>
                    <td className="py-3.5 px-3.5 font-mono font-bold text-xs text-[#1769E8]">
                      {c.appCode}
                    </td>
                    <td className="py-3.5 px-3.5">
                      <div className="font-bold text-[#071A4D] text-sm">{c.studentName}</div>
                      <div className="font-mono text-[11px] text-[#64748B]">{c.rollNumber} • {c.batch}</div>
                    </td>
                    <td className="py-3.5 px-3.5 text-[#475569]">
                      <div className="font-medium text-xs">{c.absencePeriod}</div>
                      <div className="text-[10px] text-[#64748B]">{c.durationHours}</div>
                    </td>
                    <td className="py-3.5 px-3.5 text-center font-mono font-bold text-[#071A4D]">
                      {c.hoursNumber.toFixed(1)}h
                    </td>
                    <td className="py-3.5 px-3.5 text-[#475569] max-w-[200px] truncate" title={c.diagnosis}>
                      {c.diagnosis}
                    </td>
                    <td className="py-3.5 px-3.5 text-center">
                      {c.cmoEndorsed ? (
                        <span className="inline-flex items-center gap-1 text-[11px] font-bold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-full border border-emerald-200">
                          <CheckCircle2 className="w-3 h-3" />
                          Endorsed
                        </span>
                      ) : (
                        <span className="inline-flex items-center gap-1 text-[11px] font-bold text-amber-700 bg-amber-50 px-2 py-0.5 rounded-full border border-amber-200">
                          <Clock className="w-3 h-3" />
                          Pending CMO
                        </span>
                      )}
                    </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 ${
                          c.status === "Approved"
                            ? "bg-emerald-50 text-emerald-700 border-emerald-200"
                            : c.status === "Pending"
                            ? "bg-amber-50 text-amber-700 border-amber-200"
                            : "bg-rose-50 text-rose-700 border-rose-200"
                        }`}
                      >
                        {c.status}
                      </span>
                    </td>
                    <td className="py-3.5 px-4 text-right">
                      <div className="flex items-center justify-end gap-1.5">
                        {c.status === "Pending" ? (
                          <>
                            <button
                              onClick={() => handleApprove(c.id)}
                              className="px-2.5 py-1 bg-emerald-600 hover:bg-emerald-700 text-white rounded text-[11px] font-semibold transition-colors cursor-pointer"
                            >
                              Approve
                            </button>
                            <button
                              onClick={() => handleReject(c.id)}
                              className="px-2.5 py-1 bg-rose-50 border border-rose-200 text-rose-700 hover:bg-rose-100 rounded text-[11px] font-semibold transition-colors cursor-pointer"
                            >
                              Reject
                            </button>
                          </>
                        ) : (
                          <button
                            onClick={() => setSelectedCase(c)}
                            className="px-2.5 py-1 bg-slate-100 hover:bg-slate-200 text-slate-700 rounded text-[11px] font-semibold transition-colors flex items-center gap-1 cursor-pointer"
                          >
                            <Eye className="w-3 h-3" />
                            <span>Details</span>
                          </button>
                        )}
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
