"use client";

import * as React from "react";
import {
  Users,
  CheckCircle2,
  Calendar,
  Save,
  Check,
  History,
  FileSpreadsheet,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import { Select } from "@/components/ui/select";
import { formatDateID } from "@/lib/utils";

interface TeacherAttendanceClientProps {
  teacherSubjects: any[];
}

export default function TeacherAttendanceClient({
  teacherSubjects,
}: TeacherAttendanceClientProps) {
  const [selectedTSId, setSelectedTSId] = React.useState(teacherSubjects[0]?.id || "");
  const [meetingNumber, setMeetingNumber] = React.useState("2");
  const [topic, setTopic] = React.useState("");
  const [isSaving, setIsSaving] = React.useState(false);
  const [saveMessage, setSaveMessage] = React.useState("");

  const currentTS = teacherSubjects.find((ts) => ts.id === selectedTSId);
  const students = currentTS?.class?.members?.map((m: any) => m.student) || [];

  // Attendance Records State
  const [records, setRecords] = React.useState<{ [studentId: string]: { status: string; note: string } }>({});

  // Initialize students to PRESENT
  React.useEffect(() => {
    const initialMap: any = {};
    students.forEach((s: any) => {
      initialMap[s.id] = { status: "PRESENT", note: "" };
    });
    setRecords(initialMap);
  }, [selectedTSId]);

  const setAllStatus = (status: string) => {
    const updated: any = {};
    students.forEach((s: any) => {
      updated[s.id] = { ...records[s.id], status };
    });
    setRecords(updated);
  };

  const handleStatusChange = (studentId: string, status: string) => {
    setRecords((prev) => ({
      ...prev,
      [studentId]: { ...prev[studentId], status },
    }));
  };

  const handleNoteChange = (studentId: string, note: string) => {
    setRecords((prev) => ({
      ...prev,
      [studentId]: { ...prev[studentId], note },
    }));
  };

  const handleSaveAttendance = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsSaving(true);
    setSaveMessage("");

    const recordsPayload = students.map((s: any) => ({
      studentId: s.id,
      status: records[s.id]?.status || "PRESENT",
      note: records[s.id]?.note || null,
    }));

    try {
      const res = await fetch("/api/attendance", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          teacherSubjectId: selectedTSId,
          meetingNumber: parseInt(meetingNumber) || 1,
          topic,
          records: recordsPayload,
        }),
      });

      const data = await res.json();
      setIsSaving(false);
      if (res.ok && data.success) {
        setSaveMessage(data.message || "Presensi berhasil disimpan!");
        window.location.reload();
      } else {
        alert(data.error || "Gagal menyimpan presensi.");
      }
    } catch (err) {
      setIsSaving(false);
      alert("Terjadi kesalahan jaringan.");
    }
  };

  return (
    <div className="space-y-6">
      {/* Top Filter and Configuration Form */}
      <Card className="p-5">
        <form onSubmit={handleSaveAttendance} className="space-y-4">
          <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
            <div className="sm:col-span-2">
              <Select
                label="Pilih Kelas & Mata Pelajaran"
                value={selectedTSId}
                onChange={(e) => setSelectedTSId(e.target.value)}
              >
                {teacherSubjects.map((ts) => (
                  <option key={ts.id} value={ts.id}>
                    {ts.subject.name} - Kelas {ts.class.name} ({ts.class.members.length} Siswa)
                  </option>
                ))}
              </Select>
            </div>
            <div>
              <Input
                label="Pertemuan Ke-"
                type="number"
                min="1"
                value={meetingNumber}
                onChange={(e) => setMeetingNumber(e.target.value)}
                required
              />
            </div>
          </div>

          <Input
            label="Topik / Pokok Bahasan Pertemuan"
            placeholder="Contoh: Sifat Logaritma & Penerapannya dalam Perhitungan Sains"
            value={topic}
            onChange={(e) => setTopic(e.target.value)}
          />

          {/* Quick Shortcuts */}
          <div className="flex flex-wrap items-center justify-between gap-3 pt-2 border-t border-slate-100">
            <div className="flex items-center gap-2">
              <span className="text-xs font-bold text-slate-700">Set Massal:</span>
              <Button
                type="button"
                size="sm"
                variant="outline"
                className="text-xs font-semibold text-emerald-700 bg-emerald-50 hover:bg-emerald-100 border-emerald-200"
                onClick={() => setAllStatus("PRESENT")}
              >
                <Check className="mr-1 h-3.5 w-3.5" />
                Semua Hadir
              </Button>
            </div>

            <Button type="submit" size="sm" isLoading={isSaving} className="font-bold text-xs">
              <Save className="mr-1.5 h-3.5 w-3.5" />
              Simpan Presensi Pertemuan
            </Button>
          </div>
        </form>
      </Card>

      {/* Student Attendance Table */}
      <Card>
        <CardHeader className="pb-3 border-b border-slate-100 flex flex-row items-center justify-between">
          <div>
            <CardTitle>
              Lembar Presensi Kelas {currentTS?.class?.name} - Pertemuan {meetingNumber}
            </CardTitle>
            <p className="text-xs text-slate-500 mt-0.5">
              Tandai status kehadiran setiap siswa
            </p>
          </div>
          <Badge variant="primary">{students.length} Siswa Terdaftar</Badge>
        </CardHeader>

        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <table className="w-full text-xs text-left">
              <thead className="bg-slate-50 text-slate-600 font-bold border-b border-slate-200">
                <tr>
                  <th className="py-3 px-4">No</th>
                  <th className="py-3 px-4">NIS</th>
                  <th className="py-3 px-4">Nama Lengkap Siswa</th>
                  <th className="py-3 px-4 text-center">Hadir (H)</th>
                  <th className="py-3 px-4 text-center">Sakit (S)</th>
                  <th className="py-3 px-4 text-center">Izin (I)</th>
                  <th className="py-3 px-4 text-center">Alpa (A)</th>
                  <th className="py-3 px-4">Keterangan / Catatan</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {students.map((s: any, idx: number) => {
                  const currentStatus = records[s.id]?.status || "PRESENT";
                  const currentNote = records[s.id]?.note || "";

                  return (
                    <tr key={s.id} className="hover:bg-slate-50/80 transition-colors">
                      <td className="py-2.5 px-4 text-slate-400 font-mono">{idx + 1}</td>
                      <td className="py-2.5 px-4 font-mono font-semibold text-slate-700">
                        {s.nis}
                      </td>
                      <td className="py-2.5 px-4 font-bold text-slate-900">
                        {s.fullName}
                      </td>

                      {/* Radio buttons for H, S, I, A */}
                      <td className="py-2.5 px-4 text-center">
                        <input
                          type="radio"
                          name={`status-${s.id}`}
                          checked={currentStatus === "PRESENT"}
                          onChange={() => handleStatusChange(s.id, "PRESENT")}
                          className="h-4 w-4 text-emerald-600 focus:ring-emerald-500 cursor-pointer"
                        />
                      </td>

                      <td className="py-2.5 px-4 text-center">
                        <input
                          type="radio"
                          name={`status-${s.id}`}
                          checked={currentStatus === "SICK"}
                          onChange={() => handleStatusChange(s.id, "SICK")}
                          className="h-4 w-4 text-amber-600 focus:ring-amber-500 cursor-pointer"
                        />
                      </td>

                      <td className="py-2.5 px-4 text-center">
                        <input
                          type="radio"
                          name={`status-${s.id}`}
                          checked={currentStatus === "PERMISSION"}
                          onChange={() => handleStatusChange(s.id, "PERMISSION")}
                          className="h-4 w-4 text-blue-600 focus:ring-blue-500 cursor-pointer"
                        />
                      </td>

                      <td className="py-2.5 px-4 text-center">
                        <input
                          type="radio"
                          name={`status-${s.id}`}
                          checked={currentStatus === "ABSENT"}
                          onChange={() => handleStatusChange(s.id, "ABSENT")}
                          className="h-4 w-4 text-rose-600 focus:ring-rose-500 cursor-pointer"
                        />
                      </td>

                      <td className="py-2.5 px-4">
                        <input
                          type="text"
                          placeholder="Keterangan surat / alasan..."
                          value={currentNote}
                          onChange={(e) => handleNoteChange(s.id, e.target.value)}
                          className="w-full text-xs px-2.5 py-1 rounded-lg border border-slate-200 focus:outline-none focus:ring-1 focus:ring-blue-500"
                        />
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </CardContent>
      </Card>

      {/* History of Past Meetings */}
      {currentTS?.attendances?.length > 0 && (
        <Card className="p-5 space-y-3">
          <div className="flex items-center gap-2 border-b border-slate-100 pb-2">
            <History className="h-4 w-4 text-blue-600" />
            <h4 className="text-xs font-bold text-slate-900">
              Riwayat Presensi Pertemuan Sebelumnya
            </h4>
          </div>

          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-3">
            {currentTS.attendances.map((att: any) => {
              const presentCount = att.records.filter((r: any) => r.status === "PRESENT").length;
              return (
                <div
                  key={att.id}
                  className="p-3 rounded-xl border border-slate-200 bg-white space-y-1.5 text-xs"
                >
                  <div className="flex items-center justify-between">
                    <span className="font-bold text-slate-800">
                      Pertemuan ke-{att.meetingNumber}
                    </span>
                    <Badge variant="success">{presentCount} Hadir</Badge>
                  </div>
                  <p className="text-[11px] text-slate-500 font-mono">
                    Tanggal: {formatDateID(att.date)}
                  </p>
                  {att.topic && (
                    <p className="text-[11px] text-slate-600 truncate">
                      Topik: {att.topic}
                    </p>
                  )}
                </div>
              );
            })}
          </div>
        </Card>
      )}
    </div>
  );
}
