"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  Search,
  RotateCcw,
  Plus,
  Eye,
  Edit2,
  Trash2,
  ChevronLeft,
  ChevronRight,
  FileSpreadsheet,
  FileText,
  Sliders,
  Sparkles,
  ShieldCheck,
  CheckCircle2,
} from "lucide-react";
import { toast } from "sonner";

interface AttendancePolicyItem {
  id: string;
  version: number;
  name: string;
  minAttendancePct: number;
  warningLevelPct: number;
  criticalLevelPct: number;
  aprExclusionFloorPct: number;
  medicalMaxCeilingPct: number;
  isActive: boolean;
  effectiveFrom: string;
}

const initialPolicies: AttendancePolicyItem[] = [
  {
    id: "pol-v2",
    version: 2,
    name: "NCHMCT Standard Regulations Policy 2026",
    minAttendancePct: 75.0,
    warningLevelPct: 70.0,
    criticalLevelPct: 65.0,
    aprExclusionFloorPct: 20.0,
    medicalMaxCeilingPct: 10.0,
    isActive: true,
    effectiveFrom: "2026-07-01",
  },
  {
    id: "pol-v1",
    version: 1,
    name: "NCHMCT Transitional Guidelines 2025",
    minAttendancePct: 75.0,
    warningLevelPct: 72.0,
    criticalLevelPct: 68.0,
    aprExclusionFloorPct: 25.0,
    medicalMaxCeilingPct: 10.0,
    isActive: false,
    effectiveFrom: "2025-07-01",
  },
];

export default function AttendancePoliciesPage() {
  const [policies, setPolicies] = useState<AttendancePolicyItem[]>(initialPolicies);
  const [selectedStatus, setSelectedStatus] = useState("All Status");
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedRows, setSelectedRows] = useState<string[]>([]);
  const [pageSize, setPageSize] = useState("10");

  // Form State
  const [editingId, setEditingId] = useState<string | null>(null);
  const [formData, setFormData] = useState({
    name: "",
    minAttendancePct: 75.0,
    warningLevelPct: 70.0,
    criticalLevelPct: 65.0,
    aprExclusionFloorPct: 20.0,
    medicalMaxCeilingPct: 10.0,
    effectiveFrom: "2026-07-01",
    isActive: true,
  });

  const filteredPolicies = policies.filter((p) => {
    const matchesStatus =
      selectedStatus === "All Status" ||
      (selectedStatus === "Active" && p.isActive) ||
      (selectedStatus === "Archived" && !p.isActive);
    const matchesSearch =
      searchQuery === "" ||
      p.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      p.effectiveFrom.includes(searchQuery);
    return matchesStatus && matchesSearch;
  });

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

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

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

  const handleEdit = (p: AttendancePolicyItem) => {
    setEditingId(p.id);
    setFormData({
      name: p.name,
      minAttendancePct: p.minAttendancePct,
      warningLevelPct: p.warningLevelPct,
      criticalLevelPct: p.criticalLevelPct,
      aprExclusionFloorPct: p.aprExclusionFloorPct,
      medicalMaxCeilingPct: p.medicalMaxCeilingPct,
      effectiveFrom: p.effectiveFrom,
      isActive: p.isActive,
    });
  };

  const handleDelete = (id: string) => {
    setPolicies((prev) => prev.filter((p) => p.id !== id));
    toast.success("Policy draft removed");
  };

  const handleCancelForm = () => {
    setEditingId(null);
    setFormData({
      name: "",
      minAttendancePct: 75.0,
      warningLevelPct: 70.0,
      criticalLevelPct: 65.0,
      aprExclusionFloorPct: 20.0,
      medicalMaxCeilingPct: 10.0,
      effectiveFrom: "2026-07-01",
      isActive: true,
    });
  };

  const handleSubmitForm = (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.name) {
      toast.error("Please enter Policy Title");
      return;
    }

    if (editingId) {
      setPolicies((prev) =>
        prev.map((p) =>
          p.id === editingId
            ? {
                ...p,
                name: formData.name,
                minAttendancePct: formData.minAttendancePct,
                warningLevelPct: formData.warningLevelPct,
                criticalLevelPct: formData.criticalLevelPct,
                aprExclusionFloorPct: formData.aprExclusionFloorPct,
                medicalMaxCeilingPct: formData.medicalMaxCeilingPct,
                effectiveFrom: formData.effectiveFrom,
                isActive: formData.isActive,
              }
            : p
        )
      );
      toast.success("Policy parameters updated successfully");
    } else {
      const newPolicy: AttendancePolicyItem = {
        id: `pol-v${policies.length + 1}`,
        version: policies.length + 1,
        name: formData.name,
        minAttendancePct: formData.minAttendancePct,
        warningLevelPct: formData.warningLevelPct,
        criticalLevelPct: formData.criticalLevelPct,
        aprExclusionFloorPct: formData.aprExclusionFloorPct,
        medicalMaxCeilingPct: formData.medicalMaxCeilingPct,
        effectiveFrom: formData.effectiveFrom,
        isActive: formData.isActive,
      };
      setPolicies((prev) => [newPolicy, ...prev]);
      toast.success("New institutional policy drafted");
    }
    handleCancelForm();
  };

  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/settings/attendance" className="hover:text-[#1769E8] transition-colors">
            System Settings
          </Link>
          <span>&gt;</span>
          <span className="text-[#071A4D] font-semibold">Attendance Policies</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 Policies &amp; Thresholds
            </h1>
            <p className="text-[15px] text-[#64748B] mt-1 font-normal">
              Configure NCHMCT minimum statutory percentages, shortage warning tiers, APR exclusion floors, and medical ceilings.
            </p>
          </div>

          <div className="flex items-center gap-3">
            <button
              onClick={() => toast.success("Exporting policy parameters 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 policy handbook 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={() => {
                setEditingId(null);
                setFormData({
                  name: "",
                  minAttendancePct: 75.0,
                  warningLevelPct: 70.0,
                  criticalLevelPct: 65.0,
                  aprExclusionFloorPct: 20.0,
                  medicalMaxCeilingPct: 10.0,
                  effectiveFrom: "2026-07-01",
                  isActive: true,
                });
              }}
              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"
            >
              <Plus className="w-4 h-4" />
              <span>+ Draft New Policy</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">
              Policy 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>Active</option>
              <option>Archived</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 policy name, version, or effective date..."
                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 ${filteredPolicies.length} policies`)}
              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">
              <Sliders className="w-5 h-5 text-[#1769E8]" />
              <h2 className="font-heading font-bold text-lg text-[#071A4D]">
                Policy Revisions ({filteredPolicies.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 === filteredPolicies.length &&
                        filteredPolicies.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]">Policy Name</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Mandatory %</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Warning %</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Critical %</th>
                  <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Med. Cap</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]">
                {filteredPolicies.map((p, idx) => (
                  <tr
                    key={p.id}
                    className={`hover:bg-[#F8FAFC] transition-colors ${
                      selectedRows.includes(p.id) ? "bg-[#EFF6FF]/40" : ""
                    }`}
                  >
                    <td className="py-3.5 px-3.5 text-center">
                      <input
                        type="checkbox"
                        checked={selectedRows.includes(p.id)}
                        onChange={() => handleRowSelect(p.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="flex items-center gap-1.5">
                        <span className="font-mono font-bold text-[10px] bg-[#F1F6FC] text-[#1769E8] px-1.5 py-0.5 rounded border border-[#D0E2FF]">
                          v{p.version}
                        </span>
                        <span className="font-bold text-[#071A4D] text-sm">{p.name}</span>
                      </div>
                      <div className="text-[10px] text-[#64748B] mt-0.5 font-mono">
                        Effective: {p.effectiveFrom}
                      </div>
                    </td>
                    <td className="py-3.5 px-3.5 text-center font-mono font-bold text-sm text-[#071A4D]">
                      {p.minAttendancePct.toFixed(1)}%
                    </td>
                    <td className="py-3.5 px-3.5 text-center font-mono font-bold text-amber-600">
                      {p.warningLevelPct.toFixed(1)}%
                    </td>
                    <td className="py-3.5 px-3.5 text-center font-mono font-bold text-rose-600">
                      {p.criticalLevelPct.toFixed(1)}%
                    </td>
                    <td className="py-3.5 px-3.5 text-center font-mono font-bold text-[#1769E8]">
                      {p.medicalMaxCeilingPct.toFixed(1)}%
                    </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 ${
                          p.isActive
                            ? "bg-[#DCFCE7] text-[#15803D] border-[#BBF7D0]"
                            : "bg-slate-100 text-slate-600 border-slate-200"
                        }`}
                      >
                        {p.isActive ? "Active Policy" : "Archived"}
                      </span>
                    </td>
                    <td className="py-3.5 px-4 text-right">
                      <div className="flex items-center justify-end gap-1.5">
                        <button
                          onClick={() => handleEdit(p)}
                          className="p-1.5 text-[#64748B] hover:text-[#1769E8] hover:bg-[#EFF6FF] rounded-md transition-colors cursor-pointer"
                          title="Edit Policy"
                        >
                          <Edit2 className="w-3.5 h-3.5" />
                        </button>
                        <button
                          onClick={() => handleDelete(p.id)}
                          className="p-1.5 text-[#64748B] hover:text-rose-600 hover:bg-rose-50 rounded-md transition-colors cursor-pointer"
                          title="Delete Policy"
                        >
                          <Trash2 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 {filteredPolicies.length} of {policies.length} policies
            </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): Form + Guidelines */}
        <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">
                <Sliders className="w-4 h-4 text-[#1769E8]" />
                <h3 className="font-heading font-bold text-base text-[#071A4D]">
                  {editingId ? "Edit Policy" : "Draft New Policy"}
                </h3>
              </div>
              {editingId && (
                <span className="text-[10px] font-bold px-2 py-0.5 bg-amber-50 text-amber-700 border border-amber-200 rounded-full">
                  Editing
                </span>
              )}
            </div>

            <form onSubmit={handleSubmitForm} className="space-y-4 text-xs">
              <div>
                <label className="block font-semibold text-[#334155] mb-1">
                  Policy Name <span className="text-rose-500">*</span>
                </label>
                <input
                  type="text"
                  required
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="e.g. NCHMCT Revised Policy 2027"
                  className="w-full px-3 py-2 border border-[#E2E8F0] rounded-lg text-sm text-[#0F172A] placeholder:text-[#94A3B8] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all"
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block font-semibold text-[#334155] mb-1">
                    Mandatory %
                  </label>
                  <input
                    type="number"
                    step="0.5"
                    value={formData.minAttendancePct}
                    onChange={(e) =>
                      setFormData({
                        ...formData,
                        minAttendancePct: parseFloat(e.target.value) || 0,
                      })
                    }
                    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">
                    Warning %
                  </label>
                  <input
                    type="number"
                    step="0.5"
                    value={formData.warningLevelPct}
                    onChange={(e) =>
                      setFormData({
                        ...formData,
                        warningLevelPct: parseFloat(e.target.value) || 0,
                      })
                    }
                    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 className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block font-semibold text-[#334155] mb-1">
                    Critical %
                  </label>
                  <input
                    type="number"
                    step="0.5"
                    value={formData.criticalLevelPct}
                    onChange={(e) =>
                      setFormData({
                        ...formData,
                        criticalLevelPct: parseFloat(e.target.value) || 0,
                      })
                    }
                    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">
                    Med. Ceiling %
                  </label>
                  <input
                    type="number"
                    step="0.5"
                    value={formData.medicalMaxCeilingPct}
                    onChange={(e) =>
                      setFormData({
                        ...formData,
                        medicalMaxCeilingPct: parseFloat(e.target.value) || 0,
                      })
                    }
                    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">
                  Effective From
                </label>
                <input
                  type="date"
                  value={formData.effectiveFrom}
                  onChange={(e) =>
                    setFormData({ ...formData, effectiveFrom: 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 className="flex items-center justify-between pt-2">
                <span className="font-semibold text-[#334155]">Set as Active Statutory Policy</span>
                <button
                  type="button"
                  onClick={() => setFormData({ ...formData, isActive: !formData.isActive })}
                  className={`w-11 h-6 flex items-center rounded-full p-1 transition-colors cursor-pointer ${
                    formData.isActive ? "bg-[#1769E8]" : "bg-slate-300"
                  }`}
                >
                  <div
                    className={`bg-white w-4 h-4 rounded-full shadow-md transform transition-transform ${
                      formData.isActive ? "translate-x-5" : "translate-x-0"
                    }`}
                  />
                </button>
              </div>

              <div className="flex items-center gap-2 pt-3 border-t border-[#E5EAF0]">
                <button
                  type="button"
                  onClick={handleCancelForm}
                  className="flex-1 py-2 px-3 border border-[#E2E8F0] text-[#64748B] hover:bg-slate-50 rounded-lg text-xs font-semibold transition-colors cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="flex-1 py-2 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"
                >
                  <Sliders className="w-3.5 h-3.5" />
                  <span>{editingId ? "Update" : "Save Policy"}</span>
                </button>
              </div>
            </form>
          </div>

          {/* Statutory Policy Standards 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 Regulatory Policy Framework</span>
            </div>
            <div className="space-y-2 text-[#475569]">
              <div className="flex items-center justify-between">
                <span className="font-medium">Statutory Minimum</span>
                <span className="font-mono font-bold text-[#071A4D]">75.0% Overall</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="font-medium">Medical Adjustment Cap</span>
                <span className="font-mono font-bold text-[#1769E8]">Max 10.0%</span>
              </div>
              <div className="flex items-center justify-between">
                <span className="font-medium">Duty Condonation Cap</span>
                <span className="font-mono font-bold text-amber-600">Max 5.0%</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
