"use client";

import React, { useState } from "react";
import {
  FilePlus2,
  Plus,
  Clock,
  CheckCircle2,
  XCircle,
  AlertCircle,
  FileText,
  Upload,
} from "lucide-react";
import { toast } from "sonner";

interface StudentRequestItem {
  id: string;
  type: "MEDICAL" | "DUTY_CONDONATION";
  title: string;
  dateRange: string;
  hours: number;
  status: "PENDING" | "APPROVED" | "REJECTED";
  submittedOn: string;
  reviewerRemarks?: string;
}

const initialStudentRequests: StudentRequestItem[] = [
  {
    id: "req-1",
    type: "DUTY_CONDONATION",
    title: "National Culinary Challenge 2026 Delegation",
    dateRange: "28-Sep-2026 to 29-Sep-2026",
    hours: 8.0,
    status: "APPROVED",
    submittedOn: "2026-09-27",
    reviewerRemarks: "Approved by Principal. Certificate verified.",
  },
  {
    id: "req-2",
    type: "MEDICAL",
    title: "Viral Fever Outpatient Rest (Civil Hospital)",
    dateRange: "01-Oct-2026 to 03-Oct-2026",
    hours: 12.0,
    status: "PENDING",
    submittedOn: "2026-10-04",
    reviewerRemarks: "Under review by Institutional Medical Officer.",
  },
];

export default function StudentRequestsPage() {
  const [requests, setRequests] = useState<StudentRequestItem[]>(initialStudentRequests);
  const [activeTab, setActiveTab] = useState<"NEW_MEDICAL" | "NEW_CONDONATION" | "LIST">("LIST");

  // Form State - Medical
  const [medStartDate, setMedStartDate] = useState("");
  const [medEndDate, setMedEndDate] = useState("");
  const [medHours, setMedHours] = useState(8.0);
  const [medCertFile, setMedCertFile] = useState("");
  const [medReason, setMedReason] = useState("");

  // Form State - Duty
  const [dutyEventName, setDutyEventName] = useState("");
  const [dutyDate, setDutyDate] = useState("");
  const [dutyHours, setDutyHours] = useState(4.0);
  const [dutyDept, setDutyDept] = useState("Food Production");
  const [dutyReason, setDutyReason] = useState("");

  const handleMedicalSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!medStartDate || !medEndDate || !medReason) {
      toast.error("Please fill in all required medical leave fields.");
      return;
    }

    const newReq: StudentRequestItem = {
      id: `req-${Date.now()}`,
      type: "MEDICAL",
      title: `Medical Leave (${medReason})`,
      dateRange: `${medStartDate} to ${medEndDate}`,
      hours: medHours,
      status: "PENDING",
      submittedOn: new Date().toISOString().split("T")[0],
      reviewerRemarks: "Submitted to Chief Medical Officer for vetting.",
    };

    setRequests((prev) => [newReq, ...prev]);
    toast.success("Medical slip submitted successfully. Awaiting doctor verification.");
    setActiveTab("LIST");
  };

  const handleDutySubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!dutyEventName || !dutyDate) {
      toast.error("Please provide the event name and date.");
      return;
    }

    const newReq: StudentRequestItem = {
      id: `req-${Date.now()}`,
      type: "DUTY_CONDONATION",
      title: `${dutyEventName} (${dutyDept})`,
      dateRange: dutyDate,
      hours: dutyHours,
      status: "PENDING",
      submittedOn: new Date().toISOString().split("T")[0],
      reviewerRemarks: "Forwarded to Department Head for duty confirmation.",
    };

    setRequests((prev) => [newReq, ...prev]);
    toast.success("Duty condonation claim submitted for approval.");
    setActiveTab("LIST");
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 border-b border-slate-200 pb-4 dark:border-slate-800">
        <div>
          <div className="flex items-center gap-1.5 text-xs text-slate-500 mb-0.5">
            <FilePlus2 className="w-3.5 h-3.5" />
            <span>Attendance Adjustments</span>
          </div>
          <h1 className="text-xl font-bold text-slate-900 tracking-tight dark:text-slate-100">
            Leave & Institutional Duty Condonation Claims
          </h1>
          <p className="text-xs text-slate-500 mt-0.5">
            Submit medical fitness certificates or institutional catering duty claims to offset absence hours.
          </p>
        </div>

        <div className="flex items-center gap-2 self-start sm:self-auto">
          <button
            onClick={() => setActiveTab("NEW_MEDICAL")}
            className="px-3 py-1.5 text-xs font-semibold text-white bg-blue-600 rounded hover:bg-blue-700 shadow-sm"
          >
            + Medical Slip
          </button>
          <button
            onClick={() => setActiveTab("NEW_CONDONATION")}
            className="px-3 py-1.5 text-xs font-semibold text-slate-800 bg-white border border-slate-300 rounded hover:bg-slate-50 shadow-sm dark:bg-slate-800 dark:border-slate-700 dark:text-slate-200"
          >
            + Duty Claim
          </button>
        </div>
      </div>

      {/* Tabs */}
      <div className="flex items-center gap-2 border-b border-slate-200 dark:border-slate-800">
        <button
          onClick={() => setActiveTab("LIST")}
          className={`pb-2 px-1 text-xs font-semibold border-b-2 transition-colors ${
            activeTab === "LIST"
              ? "border-blue-600 text-blue-600 dark:text-blue-400 dark:border-blue-400"
              : "border-transparent text-slate-500 hover:text-slate-800 dark:hover:text-slate-200"
          }`}
        >
          My Submitted Claims ({requests.length})
        </button>
        <button
          onClick={() => setActiveTab("NEW_MEDICAL")}
          className={`pb-2 px-1 text-xs font-semibold border-b-2 transition-colors ${
            activeTab === "NEW_MEDICAL"
              ? "border-blue-600 text-blue-600 dark:text-blue-400 dark:border-blue-400"
              : "border-transparent text-slate-500 hover:text-slate-800 dark:hover:text-slate-200"
          }`}
        >
          Submit Medical Certificate
        </button>
        <button
          onClick={() => setActiveTab("NEW_CONDONATION")}
          className={`pb-2 px-1 text-xs font-semibold border-b-2 transition-colors ${
            activeTab === "NEW_CONDONATION"
              ? "border-blue-600 text-blue-600 dark:text-blue-400 dark:border-blue-400"
              : "border-transparent text-slate-500 hover:text-slate-800 dark:hover:text-slate-200"
          }`}
        >
          Submit Duty Condonation Claim
        </button>
      </div>

      {/* Content depending on active tab */}
      {activeTab === "LIST" && (
        <div className="space-y-3">
          {requests.map((req) => (
            <div
              key={req.id}
              className="p-4 rounded-lg border border-slate-200 bg-white shadow-sm flex flex-col sm:flex-row sm:items-center justify-between gap-3 dark:border-slate-800 dark:bg-slate-900"
            >
              <div>
                <div className="flex items-center gap-2 mb-1">
                  <span
                    className={`text-[10px] font-bold uppercase tracking-wider px-2 py-0.5 rounded border ${
                      req.type === "MEDICAL"
                        ? "bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-950/40 dark:text-rose-300 dark:border-rose-800"
                        : "bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-950/40 dark:text-amber-300 dark:border-amber-800"
                    }`}
                  >
                    {req.type === "MEDICAL" ? "Medical Certificate" : "Institutional Duty"}
                  </span>
                  <span className="text-xs text-slate-500 font-mono">
                    Submitted: {req.submittedOn}
                  </span>
                </div>
                <h3 className="text-sm font-bold text-slate-900 dark:text-slate-100">
                  {req.title}
                </h3>
                <p className="text-xs text-slate-500 mt-0.5">
                  Dates: {req.dateRange} • Claimed: {req.hours} Contact Hours
                </p>
                {req.reviewerRemarks && (
                  <p className="text-[11px] text-slate-600 mt-1 italic dark:text-slate-400">
                    Remark: {req.reviewerRemarks}
                  </p>
                )}
              </div>

              <div className="self-start sm:self-auto">
                <span
                  className={`inline-flex items-center px-2.5 py-1 rounded text-xs font-semibold border ${
                    req.status === "APPROVED"
                      ? "bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-950/40 dark:text-emerald-300 dark:border-emerald-800"
                      : req.status === "PENDING"
                      ? "bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-950/40 dark:text-amber-300 dark:border-amber-800"
                      : "bg-rose-50 text-rose-700 border-rose-200 dark:bg-rose-950/40 dark:text-rose-300 dark:border-rose-800"
                  }`}
                >
                  {req.status}
                </span>
              </div>
            </div>
          ))}
        </div>
      )}

      {activeTab === "NEW_MEDICAL" && (
        <div className="max-w-xl p-5 rounded-lg border border-slate-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900">
          <h2 className="text-sm font-bold text-slate-900 mb-1 dark:text-slate-100">
            Submit Medical Fitness Certificate
          </h2>
          <p className="text-xs text-slate-500 mb-4">
            Under NCHMCT policy, medical leave is capped at maximum 10% of total semester contact hours.
          </p>

          <form onSubmit={handleMedicalSubmit} className="space-y-4">
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
                  Leave Start Date *
                </label>
                <input
                  type="date"
                  required
                  value={medStartDate}
                  onChange={(e) => setMedStartDate(e.target.value)}
                  className="w-full px-3 py-2 text-xs rounded border border-slate-200 bg-white font-mono focus:outline-none focus:ring-1 focus:ring-blue-600 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-100"
                />
              </div>
              <div>
                <label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
                  Leave End Date *
                </label>
                <input
                  type="date"
                  required
                  value={medEndDate}
                  onChange={(e) => setMedEndDate(e.target.value)}
                  className="w-full px-3 py-2 text-xs rounded border border-slate-200 bg-white font-mono focus:outline-none focus:ring-1 focus:ring-blue-600 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-100"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
                  Estimated Missed Hours *
                </label>
                <input
                  type="number"
                  step="0.5"
                  min="1"
                  max="18"
                  value={medHours}
                  onChange={(e) => setMedHours(parseFloat(e.target.value) || 1)}
                  className="w-full px-3 py-2 text-xs rounded border border-slate-200 bg-white font-mono focus:outline-none focus:ring-1 focus:ring-blue-600 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-100"
                />
              </div>
              <div>
                <label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
                  Medical Certificate File (PDF / JPG) *
                </label>
                <input
                  type="file"
                  accept=".pdf, .jpg, .jpeg, .png"
                  onChange={(e) => setMedCertFile(e.target.files?.[0]?.name || "")}
                  className="w-full text-xs text-slate-500 file:mr-2 file:py-1.5 file:px-3 file:rounded file:border-0 file:text-xs file:font-semibold file:bg-slate-100 file:text-slate-700 hover:file:bg-slate-200"
                />
              </div>
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
                Medical Diagnosis / Treatment Summary *
              </label>
              <textarea
                required
                rows={2}
                value={medReason}
                onChange={(e) => setMedReason(e.target.value)}
                placeholder="e.g. Acute viral gastroenteritis with outpatient hospital treatment..."
                className="w-full px-3 py-2 text-xs rounded border border-slate-200 bg-white focus:outline-none focus:ring-1 focus:ring-blue-600 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-100"
              />
            </div>

            <div className="flex items-center justify-end gap-2 pt-3 border-t border-slate-200 dark:border-slate-800">
              <button
                type="button"
                onClick={() => setActiveTab("LIST")}
                className="px-3 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-100 rounded border border-slate-200 dark:text-slate-300 dark:border-slate-700 dark:hover:bg-slate-800"
              >
                Cancel
              </button>
              <button
                type="submit"
                className="px-3.5 py-1.5 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-700 rounded shadow-sm"
              >
                Submit Medical Slip
              </button>
            </div>
          </form>
        </div>
      )}

      {activeTab === "NEW_CONDONATION" && (
        <div className="max-w-xl p-5 rounded-lg border border-slate-200 bg-white shadow-sm dark:border-slate-800 dark:bg-slate-900">
          <h2 className="text-sm font-bold text-slate-900 mb-1 dark:text-slate-100">
            Submit Institutional Duty Condonation Claim
          </h2>
          <p className="text-xs text-slate-500 mb-4">
            Claim attendance units for official state banquets, culinary competitions, or institute delegations.
          </p>

          <form onSubmit={handleDutySubmit} className="space-y-4">
            <div>
              <label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
                Event / Delegation Title *
              </label>
              <input
                type="text"
                required
                value={dutyEventName}
                onChange={(e) => setDutyEventName(e.target.value)}
                placeholder="e.g. Inter-IHM National Culinary Competition"
                className="w-full px-3 py-2 text-xs rounded border border-slate-200 bg-white focus:outline-none focus:ring-1 focus:ring-blue-600 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-100"
              />
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
                  Duty Date *
                </label>
                <input
                  type="date"
                  required
                  value={dutyDate}
                  onChange={(e) => setDutyDate(e.target.value)}
                  className="w-full px-3 py-2 text-xs rounded border border-slate-200 bg-white font-mono focus:outline-none focus:ring-1 focus:ring-blue-600 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-100"
                />
              </div>
              <div>
                <label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
                  Contact Hours Claimed *
                </label>
                <input
                  type="number"
                  step="0.5"
                  min="1"
                  max="16"
                  value={dutyHours}
                  onChange={(e) => setDutyHours(parseFloat(e.target.value) || 1)}
                  className="w-full px-3 py-2 text-xs rounded border border-slate-200 bg-white font-mono focus:outline-none focus:ring-1 focus:ring-blue-600 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-100"
                />
              </div>
            </div>

            <div>
              <label className="block text-xs font-semibold text-slate-700 dark:text-slate-300 mb-1">
                Deputing Department *
              </label>
              <select
                value={dutyDept}
                onChange={(e) => setDutyDept(e.target.value)}
                className="w-full px-3 py-2 text-xs rounded border border-slate-200 bg-white focus:outline-none focus:ring-1 focus:ring-blue-600 dark:border-slate-800 dark:bg-slate-950 dark:text-slate-100"
              >
                <option value="Food Production">Food Production Department</option>
                <option value="F&B Service">F&B Service Department</option>
                <option value="Front Office">Front Office Department</option>
                <option value="Student Welfare">Student Welfare Committee</option>
              </select>
            </div>

            <div className="flex items-center justify-end gap-2 pt-3 border-t border-slate-200 dark:border-slate-800">
              <button
                type="button"
                onClick={() => setActiveTab("LIST")}
                className="px-3 py-1.5 text-xs font-medium text-slate-600 hover:bg-slate-100 rounded border border-slate-200 dark:text-slate-300 dark:border-slate-700 dark:hover:bg-slate-800"
              >
                Cancel
              </button>
              <button
                type="submit"
                className="px-3.5 py-1.5 text-xs font-semibold text-white bg-blue-600 hover:bg-blue-700 rounded shadow-sm"
              >
                Submit Condonation Claim
              </button>
            </div>
          </form>
        </div>
      )}
    </div>
  );
}
