"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  HeartPulse,
  CheckCircle2,
  XCircle,
  Clock,
  ChevronRight,
  FileText,
  Search,
  Filter,
  Eye,
  AlertTriangle,
  X,
  Sparkles,
} from "lucide-react";
import { toast } from "sonner";

interface MedicalRequest {
  id: string;
  rollNo: string;
  studentName: string;
  semester: number;
  batch: string;
  hospitalName: string;
  doctorName: string;
  startDate: string;
  endDate: string;
  totalDays: number;
  impactedSessions: number;
  currentAttendance: number;
  projectedAttendance: number;
  certificateRef: string;
  reason: string;
  status: "PENDING" | "APPROVED" | "REJECTED";
  adminRemarks?: string;
}

export default function DeptAdminMedicalAdjustmentsPage() {
  const [requests, setRequests] = useState<MedicalRequest[]>([
    {
      id: "med_1",
      rollNo: "2441112015",
      studentName: "Debashis Sen",
      semester: 3,
      batch: "Kitchen Batch Q1",
      hospitalName: "AMRI Hospitals, Salt Lake",
      doctorName: "Dr. K. S. Sengupta (MD)",
      startDate: "08 Oct 2024",
      endDate: "12 Oct 2024",
      totalDays: 5,
      impactedSessions: 18,
      currentAttendance: 71.2,
      projectedAttendance: 79.4,
      certificateRef: "CERT-MED-2441112015.pdf",
      reason: "Acute viral gastroenteritis and mandatory hydration rest.",
      status: "PENDING",
    },
    {
      id: "med_2",
      rollNo: "2441112089",
      studentName: "Rahul Roychowdhury",
      semester: 5,
      batch: "Kitchen Batch A1",
      hospitalName: "Apollo Multispeciality Hospitals",
      doctorName: "Dr. R. Banerjee (Ortho)",
      startDate: "01 Oct 2024",
      endDate: "05 Oct 2024",
      totalDays: 5,
      impactedSessions: 16,
      currentAttendance: 67.8,
      projectedAttendance: 76.1,
      certificateRef: "CERT-MED-2441112089.pdf",
      reason: "Hairline fracture right wrist during sports practice.",
      status: "PENDING",
    },
    {
      id: "med_3",
      rollNo: "2441112055",
      studentName: "Sneha Chatterjee",
      semester: 1,
      batch: "Kitchen Batch K2",
      hospitalName: "Fortis Hospital Anandapur",
      doctorName: "Dr. P. Roy (Physician)",
      startDate: "16 Sep 2024",
      endDate: "18 Sep 2024",
      totalDays: 3,
      impactedSessions: 10,
      currentAttendance: 73.0,
      projectedAttendance: 78.2,
      certificateRef: "CERT-MED-2441112055.pdf",
      reason: "Severe allergic bronchospasm & asthma exacerbation.",
      status: "PENDING",
    },
    {
      id: "med_4",
      rollNo: "2441112002",
      studentName: "Ananya Mukherjee",
      semester: 1,
      batch: "Kitchen Batch K1",
      hospitalName: "Woodlands Hospital",
      doctorName: "Dr. S. Das",
      startDate: "02 Sep 2024",
      endDate: "04 Sep 2024",
      totalDays: 3,
      impactedSessions: 9,
      currentAttendance: 88.5,
      projectedAttendance: 92.4,
      certificateRef: "CERT-MED-2441112002.pdf",
      reason: "Severe migraine requiring clinical observation.",
      status: "APPROVED",
      adminRemarks: "Approved as per certified medical documents.",
    },
  ]);

  const [activeTab, setActiveTab] = useState<"PENDING" | "APPROVED" | "REJECTED">("PENDING");
  const [selectedReq, setSelectedReq] = useState<MedicalRequest | null>(null);
  const [remarks, setRemarks] = useState("");
  const [actionType, setActionType] = useState<"APPROVE" | "REJECT" | "VIEW" | null>(null);

  const filtered = requests.filter((r) => r.status === activeTab);

  const handleApprove = () => {
    if (!selectedReq) return;
    setRequests(
      requests.map((r) =>
        r.id === selectedReq.id
          ? {
              ...r,
              status: "APPROVED",
              currentAttendance: r.projectedAttendance,
              adminRemarks: remarks || "Approved after HOD verification",
            }
          : r
      )
    );
    setActionType(null);
    setSelectedReq(null);
    setRemarks("");
    toast.success(`Medical adjustment approved for ${selectedReq.studentName}. Attendance updated to ${selectedReq.projectedAttendance}%.`);
  };

  const handleReject = () => {
    if (!selectedReq) return;
    if (!remarks.trim()) {
      toast.error("Please enter rejection remarks");
      return;
    }
    setRequests(
      requests.map((r) =>
        r.id === selectedReq.id
          ? {
              ...r,
              status: "REJECTED",
              adminRemarks: remarks,
            }
          : r
      )
    );
    setActionType(null);
    setSelectedReq(null);
    setRemarks("");
    toast.info(`Medical request rejected for ${selectedReq.studentName}`);
  };

  return (
    <div className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl mx-auto">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-2 text-xs font-semibold text-slate-500 mb-1">
            <Link href="/dept-admin/dashboard" className="hover:text-[#1769E8]">
              Dashboard
            </Link>
            <ChevronRight className="w-3.5 h-3.5" />
            <span className="text-[#071A4D] font-bold">Medical Adjustments</span>
          </div>
          <h1 className="text-xl sm:text-2xl font-black text-[#071A4D] tracking-tight">
            Medical Leave & Attendance Adjustments
          </h1>
          <p className="text-xs text-slate-500 mt-0.5">
            Review student clinical leaves, verify hospitalization certificates, and apply attendance concession credits
          </p>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex items-center gap-2 border-b border-slate-200">
        {[
          { key: "PENDING", label: "Pending Verification", count: requests.filter((r) => r.status === "PENDING").length },
          { key: "APPROVED", label: "Approved Records", count: requests.filter((r) => r.status === "APPROVED").length },
          { key: "REJECTED", label: "Rejected Applications", count: requests.filter((r) => r.status === "REJECTED").length },
        ].map((tab) => (
          <button
            key={tab.key}
            onClick={() => setActiveTab(tab.key as any)}
            className={`pb-3 px-3 text-xs font-bold border-b-2 transition-colors flex items-center gap-1.5 ${
              activeTab === tab.key
                ? "border-[#C8A45D] text-[#071A4D]"
                : "border-transparent text-slate-500 hover:text-slate-800"
            }`}
          >
            <span>{tab.label}</span>
            <span
              className={`text-[10px] px-1.5 py-0.2 rounded-full font-bold ${
                activeTab === tab.key
                  ? "bg-[#C8A45D] text-slate-950"
                  : "bg-slate-100 text-slate-600"
              }`}
            >
              {tab.count}
            </span>
          </button>
        ))}
      </div>

      {/* Requests List */}
      <div className="space-y-4">
        {filtered.length === 0 ? (
          <div className="p-12 text-center bg-white rounded-xl border border-slate-200 text-slate-400 text-xs">
            No {activeTab.toLowerCase()} medical adjustment requests found.
          </div>
        ) : (
          filtered.map((req) => (
            <div
              key={req.id}
              className="p-5 rounded-xl bg-white border border-slate-200 shadow-xs hover:shadow-md transition-all space-y-4"
            >
              <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
                <div className="flex items-start gap-3">
                  <div className="w-10 h-10 rounded-lg bg-rose-50 text-rose-600 flex items-center justify-center shrink-0 border border-rose-200">
                    <HeartPulse className="w-5 h-5" />
                  </div>
                  <div>
                    <div className="flex items-center gap-2">
                      <h3 className="text-base font-bold text-[#071A4D]">{req.studentName}</h3>
                      <span className="font-mono text-xs font-bold bg-slate-100 text-slate-700 px-2 py-0.5 rounded-md">
                        {req.rollNo}
                      </span>
                    </div>
                    <p className="text-xs text-slate-500 mt-0.5">
                      Semester {req.semester} • {req.batch}
                    </p>
                  </div>
                </div>

                <div className="flex flex-wrap items-center gap-4 text-xs">
                  <div className="bg-slate-50 px-3 py-1.5 rounded-lg border border-slate-200">
                    <span className="text-[10px] text-slate-400 block uppercase font-semibold">Current Attendance</span>
                    <span className="font-mono font-bold text-rose-600">{req.currentAttendance}%</span>
                  </div>
                  <div className="bg-emerald-50 px-3 py-1.5 rounded-lg border border-emerald-200">
                    <span className="text-[10px] text-emerald-600 block uppercase font-semibold">After Adjustment</span>
                    <span className="font-mono font-bold text-emerald-700">{req.projectedAttendance}%</span>
                  </div>
                </div>
              </div>

              {/* Medical Details Box */}
              <div className="p-3.5 rounded-lg bg-slate-50 border border-slate-200/80 text-xs space-y-2">
                <div className="grid grid-cols-1 sm:grid-cols-3 gap-2">
                  <div>
                    <span className="text-slate-400 block text-[10px]">Medical Facility</span>
                    <span className="font-semibold text-slate-800">{req.hospitalName}</span>
                  </div>
                  <div>
                    <span className="text-slate-400 block text-[10px]">Attending Physician</span>
                    <span className="font-semibold text-slate-800">{req.doctorName}</span>
                  </div>
                  <div>
                    <span className="text-slate-400 block text-[10px]">Leave Dates & Sessions</span>
                    <span className="font-semibold text-slate-800">
                      {req.startDate} – {req.endDate} ({req.impactedSessions} Sessions)
                    </span>
                  </div>
                </div>

                <div className="pt-2 border-t border-slate-200 text-slate-600">
                  <span className="font-semibold text-slate-800">Diagnosis: </span>
                  {req.reason}
                </div>
              </div>

              {/* Actions Footer */}
              <div className="flex items-center justify-between pt-1">
                <button
                  onClick={() => {
                    setSelectedReq(req);
                    setActionType("VIEW");
                  }}
                  className="text-xs font-bold text-[#1769E8] hover:underline flex items-center gap-1"
                >
                  <Eye className="w-3.5 h-3.5" />
                  <span>View Attached Medical Certificate</span>
                </button>

                {req.status === "PENDING" && (
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => {
                        setSelectedReq(req);
                        setActionType("REJECT");
                      }}
                      className="px-3 py-1.5 rounded-lg border border-rose-200 text-rose-700 hover:bg-rose-50 text-xs font-bold"
                    >
                      Reject Application
                    </button>
                    <button
                      onClick={() => {
                        setSelectedReq(req);
                        setActionType("APPROVE");
                      }}
                      className="px-4 py-1.5 rounded-lg bg-emerald-600 text-white hover:bg-emerald-700 text-xs font-bold shadow-xs"
                    >
                      Approve & Credit {req.impactedSessions} Sessions
                    </button>
                  </div>
                )}
              </div>
            </div>
          ))
        )}
      </div>

      {/* Action Dialog */}
      {selectedReq && actionType && (
        <div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl max-w-lg w-full p-6 shadow-2xl border border-slate-200 animate-in fade-in zoom-in-95">
            <div className="flex items-center justify-between pb-3 border-b border-slate-100">
              <h3 className="font-bold text-base text-[#071A4D]">
                {actionType === "APPROVE"
                  ? "Approve Medical Adjustment"
                  : actionType === "REJECT"
                  ? "Reject Medical Application"
                  : "Medical Certificate Verification"}
              </h3>
              <button
                onClick={() => {
                  setSelectedReq(null);
                  setActionType(null);
                }}
              >
                <X className="w-5 h-5 text-slate-400" />
              </button>
            </div>

            <div className="py-4 space-y-4 text-xs">
              <div className="p-3 bg-slate-50 rounded-lg space-y-1">
                <div className="font-bold text-slate-800 text-sm">{selectedReq.studentName}</div>
                <div className="text-slate-500 font-mono">Roll: {selectedReq.rollNo}</div>
                <div className="text-slate-600">Hospital: {selectedReq.hospitalName}</div>
              </div>

              {actionType === "VIEW" ? (
                <div className="border border-dashed border-slate-300 p-8 rounded-xl text-center space-y-2 bg-slate-50">
                  <FileText className="w-8 h-8 text-slate-400 mx-auto" />
                  <div className="font-bold text-slate-700">{selectedReq.certificateRef}</div>
                  <div className="text-[11px] text-slate-400">
                    Official clinical discharge summary with hospital seal & registration ID
                  </div>
                </div>
              ) : (
                <div>
                  <label className="font-bold text-slate-800 block mb-1">
                    {actionType === "APPROVE" ? "Approval Remarks" : "Rejection Reason *"}
                  </label>
                  <textarea
                    rows={3}
                    placeholder={
                      actionType === "APPROVE"
                        ? "e.g. Verified with original hospital discharge slip."
                        : "e.g. Incomplete prescription / certificate not signed by registered MD."
                    }
                    value={remarks}
                    onChange={(e) => setRemarks(e.target.value)}
                    className="w-full p-2.5 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#C8A45D]"
                    required={actionType === "REJECT"}
                  />
                </div>
              )}
            </div>

            <div className="pt-3 border-t border-slate-100 flex justify-end gap-2 text-xs">
              <button
                type="button"
                onClick={() => {
                  setSelectedReq(null);
                  setActionType(null);
                }}
                className="px-4 py-2 rounded-lg border border-slate-200 font-bold text-slate-600 hover:bg-slate-50"
              >
                Close
              </button>

              {actionType === "APPROVE" && (
                <button
                  type="button"
                  onClick={handleApprove}
                  className="px-4 py-2 rounded-lg bg-emerald-600 text-white font-bold hover:bg-emerald-700"
                >
                  Confirm Approval
                </button>
              )}

              {actionType === "REJECT" && (
                <button
                  type="button"
                  onClick={handleReject}
                  className="px-4 py-2 rounded-lg bg-rose-600 text-white font-bold hover:bg-rose-700"
                >
                  Confirm Rejection
                </button>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
