"use client";

import React, { useState, useMemo } from "react";
import Link from "next/link";
import {
  Search as SearchIcon,
  RotateCcw as RotateCcwIcon,
  FileSpreadsheet as FileSpreadsheetIcon,
  FileText as FileTextIcon,
  Printer as PrinterIcon,
  Sparkles as SparklesIcon,
  Calendar as CalendarIcon,
  CheckCircle2,
} from "lucide-react";
import { toast } from "sonner";

const DAYS_IN_MONTH = 31;

interface DayCell {
  day: number;
  statusCode: "P" | "A" | "C" | "M" | "H" | "-";
}

interface StudentMatrixRow {
  id: string;
  roll: string;
  name: string;
  days: Record<number, DayCell>;
  conductedHours: number;
  attendedHours: number;
  percentage: number;
}

const mockStudents = [
  { id: "s-101", roll: "2441112001", name: "Aaron Smith" },
  { id: "s-102", roll: "2441112002", name: "Bethany Roy" },
  { id: "s-103", roll: "2441112003", name: "Chirag Banerjee" },
  { id: "s-104", roll: "2441112004", name: "Devika Sharma" },
  { id: "s-105", roll: "2441112005", name: "Farhan Ahmed" },
  { id: "s-106", roll: "2441112006", name: "Gautam Sen" },
  { id: "s-107", roll: "2441112007", name: "Harshavardhan Rao" },
  { id: "s-108", roll: "2441112008", name: "Isha Mukherjee" },
  { id: "s-109", roll: "2441112009", name: "Jayant Verma" },
  { id: "s-110", roll: "2441112010", name: "Kritika Das" },
];

function buildMatrix(): StudentMatrixRow[] {
  return mockStudents.map((s, idx) => {
    const days: Record<number, DayCell> = {};
    let conducted = 80;
    let attended = 72;

    for (let d = 1; d <= DAYS_IN_MONTH; d++) {
      if (d === 2) {
        days[d] = { day: d, statusCode: "H" }; // Gandhi Jayanti
      } else if (d % 7 === 4 || d % 7 === 0) {
        days[d] = { day: d, statusCode: "-" }; // Weekend
      } else if (idx === 8 && (d === 6 || d === 7 || d === 13)) {
        days[d] = { day: d, statusCode: "A" };
      } else if (idx === 2 && d === 9) {
        days[d] = { day: d, statusCode: "M" };
      } else if (idx === 6 && d === 12) {
        days[d] = { day: d, statusCode: "C" };
      } else {
        days[d] = { day: d, statusCode: "P" };
      }
    }

    if (idx === 8) {
      attended = 52;
    } else if (idx === 3) {
      attended = 60;
    }

    const percentage = Number(((attended / conducted) * 100).toFixed(1));

    return {
      id: s.id,
      roll: s.roll,
      name: s.name,
      days,
      conductedHours: conducted,
      attendedHours: attended,
      percentage,
    };
  });
}

export default function MonthlyMatrixPage() {
  const [data] = useState<StudentMatrixRow[]>(buildMatrix);
  const [selectedMonth, setSelectedMonth] = useState("October 2026");
  const [selectedSemester, setSelectedSemester] = useState("Semester III");
  const [selectedBatch, setSelectedBatch] = useState("Batch B1");
  const [searchQuery, setSearchQuery] = useState("");

  const filteredData = data.filter(
    (s) =>
      s.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      s.roll.includes(searchQuery)
  );

  const getCellBadge = (code: string) => {
    switch (code) {
      case "P":
        return "bg-[#DCFCE7] text-[#15803D] font-bold";
      case "A":
        return "bg-[#FEE2E2] text-[#DC2626] font-bold";
      case "C":
        return "bg-[#FEF3C7] text-[#B45309] font-bold";
      case "M":
        return "bg-[#CCFBF1] text-[#0F766E] font-bold";
      case "H":
        return "bg-slate-200 text-slate-600 font-bold";
      default:
        return "bg-slate-50 text-slate-300";
    }
  };

  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/reports/monthly-matrix" className="hover:text-[#1769E8] transition-colors">
            Reports &amp; Analytics
          </Link>
          <span>&gt;</span>
          <span className="text-[#071A4D] font-semibold">Monthly Attendance Matrix</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">
              Monthly Attendance Matrix
            </h1>
            <p className="text-[15px] text-[#64748B] mt-1 font-normal">
              High-density day-by-day attendance register across all cohort students with status codes and statutory totals.
            </p>
          </div>

          <div className="flex items-center gap-3">
            <button
              onClick={() => toast.success("Exporting full matrix register 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"
            >
              <FileSpreadsheetIcon className="w-4 h-4 text-emerald-600" />
              <span>Export</span>
            </button>
            <button
              onClick={() => toast.info("Generating official matrix 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"
            >
              <FileTextIcon className="w-4 h-4 text-purple-600" />
              <span>Generate Report</span>
            </button>
            <button
              onClick={() => window.print()}
              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"
            >
              <PrinterIcon className="w-4 h-4" />
              <span>Print Matrix</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">
              Month &amp; Year
            </label>
            <select
              value={selectedMonth}
              onChange={(e) => setSelectedMonth(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>October 2026</option>
              <option>September 2026</option>
              <option>August 2026</option>
            </select>
          </div>

          <div className="lg:col-span-3">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Academic Semester
            </label>
            <select
              value={selectedSemester}
              onChange={(e) => setSelectedSemester(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>Semester I</option>
              <option>Semester III</option>
              <option>Semester V</option>
            </select>
          </div>

          <div className="lg:col-span-4">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Search
            </label>
            <div className="relative">
              <SearchIcon 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 student name or roll number..."
                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(`Filtered ${filteredData.length} students`)}
              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"
            >
              <SearchIcon className="w-4 h-4" />
              <span>Search</span>
            </button>
            <button
              onClick={() => setSearchQuery("")}
              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"
            >
              <RotateCcwIcon className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      {/* 3. 31-Day Matrix Table */}
      <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs overflow-hidden">
        <div className="p-4 border-b border-[#E5EAF0] flex flex-col sm:flex-row sm:items-center justify-between gap-2">
          <div className="flex items-center gap-2.5">
            <CalendarIcon className="w-5 h-5 text-[#1769E8] shrink-0" />
            <h2 className="font-heading font-bold text-base sm:text-lg text-[#071A4D]">
              Day-by-Day Roster Matrix ({filteredData.length} Students)
            </h2>
          </div>
          <div className="flex items-center justify-between sm:justify-end gap-2 text-xs text-[#64748B]">
            <span className="font-mono">{selectedMonth} • {selectedSemester}</span>
            <span className="sm:hidden text-[10px] font-semibold text-[#1769E8] bg-blue-50 px-2 py-0.5 rounded-full border border-blue-100 flex items-center gap-1 shrink-0">
              Scroll &rarr;
            </span>
          </div>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs border-separate border-spacing-0">
            <thead>
              <tr className="bg-[#F8FAFC] text-[#64748B]">
                <th className="py-2.5 px-3 sticky left-0 bg-[#F8FAFC] z-30 w-[100px] min-w-[100px] max-w-[100px] font-bold text-[#071A4D] border-r border-b border-[#E5EAF0]">
                  Roll No
                </th>
                <th className="py-2.5 px-3 sticky left-[100px] bg-[#F8FAFC] z-30 w-[130px] min-w-[130px] max-w-[130px] sm:w-[170px] sm:min-w-[170px] sm:max-w-[170px] font-bold text-[#071A4D] border-r border-b border-[#E5EAF0] shadow-[2px_0_4px_-2px_rgba(0,0,0,0.08)]">
                  Student Name
                </th>
                {Array.from({ length: DAYS_IN_MONTH }, (_, i) => i + 1).map((d) => (
                  <th
                    key={d}
                    className="py-2 px-1 text-center font-mono text-[10px] w-7 min-w-[28px] border-r border-b border-[#E5EAF0] bg-[#F8FAFC]"
                  >
                    {d}
                  </th>
                ))}
                <th className="py-2.5 px-2 text-center font-bold text-[#071A4D] w-14 min-w-[48px] border-b border-[#E5EAF0] bg-[#F8FAFC]">
                  Cond.
                </th>
                <th className="py-2.5 px-2 text-center font-bold text-[#071A4D] w-14 min-w-[48px] border-b border-[#E5EAF0] bg-[#F8FAFC]">
                  Attd.
                </th>
                <th className="py-2.5 px-3 text-center font-bold text-[#071A4D] w-16 min-w-[56px] border-b border-[#E5EAF0] bg-[#F8FAFC]">
                  %
                </th>
              </tr>
            </thead>
            <tbody>
              {filteredData.map((s) => (
                <tr key={s.id} className="group hover:bg-slate-50 transition-colors">
                  <td className="py-2 px-3 sticky left-0 bg-white group-hover:bg-slate-50 z-20 font-mono font-bold text-xs text-[#1769E8] border-r border-b border-[#E5EAF0] w-[100px] min-w-[100px] max-w-[100px] truncate transition-colors">
                    {s.roll}
                  </td>
                  <td className="py-2 px-3 sticky left-[100px] bg-white group-hover:bg-slate-50 z-20 font-bold text-[#071A4D] text-xs border-r border-b border-[#E5EAF0] shadow-[2px_0_4px_-2px_rgba(0,0,0,0.08)] w-[130px] min-w-[130px] max-w-[130px] sm:w-[170px] sm:min-w-[170px] sm:max-w-[170px] truncate transition-colors">
                    {s.name}
                  </td>
                  {Array.from({ length: DAYS_IN_MONTH }, (_, i) => i + 1).map((d) => {
                    const cell = s.days[d];
                    const code = cell ? cell.statusCode : "-";
                    return (
                      <td
                        key={d}
                        className="py-1 px-0.5 text-center border-r border-b border-[#E5EAF0] bg-white group-hover:bg-slate-50 transition-colors"
                      >
                        <span
                          className={`inline-block w-5 h-5 leading-5 rounded text-[10px] ${getCellBadge(
                            code
                          )}`}
                        >
                          {code}
                        </span>
                      </td>
                    );
                  })}
                  <td className="py-2 px-2 text-center font-mono text-[#64748B] border-b border-[#E5EAF0] bg-white group-hover:bg-slate-50 transition-colors">
                    {s.conductedHours}h
                  </td>
                  <td className="py-2 px-2 text-center font-mono font-bold text-[#071A4D] border-b border-[#E5EAF0] bg-white group-hover:bg-slate-50 transition-colors">
                    {s.attendedHours}h
                  </td>
                  <td className="py-2 px-3 text-center font-mono font-bold text-xs border-b border-[#E5EAF0] bg-white group-hover:bg-slate-50 transition-colors">
                    <span
                      className={
                        s.percentage >= 75
                          ? "text-emerald-600"
                          : "text-rose-600 bg-rose-50 px-1.5 py-0.5 rounded border border-rose-200"
                      }
                    >
                      {s.percentage}%
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* 4. Legend Bar */}
      <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs p-4 flex flex-wrap items-center justify-between gap-4 text-xs">
        <div className="flex items-center gap-2 font-bold text-[#071A4D]">
          <SparklesIcon className="w-4 h-4 text-amber-500" />
          <span>Attendance Code Legend:</span>
        </div>
        <div className="flex items-center gap-4 flex-wrap">
          <div className="flex items-center gap-1.5">
            <span className="w-5 h-5 rounded text-[10px] flex items-center justify-center bg-[#DCFCE7] text-[#15803D] font-bold">
              P
            </span>
            <span className="text-[#475569]">Present</span>
          </div>
          <div className="flex items-center gap-1.5">
            <span className="w-5 h-5 rounded text-[10px] flex items-center justify-center bg-[#FEE2E2] text-[#DC2626] font-bold">
              A
            </span>
            <span className="text-[#475569]">Absent</span>
          </div>
          <div className="flex items-center gap-1.5">
            <span className="w-5 h-5 rounded text-[10px] flex items-center justify-center bg-[#FEF3C7] text-[#B45309] font-bold">
              C
            </span>
            <span className="text-[#475569]">Duty Condoned</span>
          </div>
          <div className="flex items-center gap-1.5">
            <span className="w-5 h-5 rounded text-[10px] flex items-center justify-center bg-[#CCFBF1] text-[#0F766E] font-bold">
              M
            </span>
            <span className="text-[#475569]">Medical Leave</span>
          </div>
          <div className="flex items-center gap-1.5">
            <span className="w-5 h-5 rounded text-[10px] flex items-center justify-center bg-slate-200 text-slate-600 font-bold">
              H
            </span>
            <span className="text-[#475569]">Gazetted Holiday</span>
          </div>
        </div>
      </div>
    </div>
  );
}
