"use client";

import * as React from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Printer, ChevronLeft, ChevronRight, UserCheck } from "lucide-react";

interface SubjectGrade {
  subjectName: string;
  teacherName: string;
  kkm: number;
  score: number;
  letter: string;
  description: string;
}

interface StudentReport {
  id: string;
  nis: string;
  nisn: string;
  fullName: string;
  attendance: {
    sick: number;
    permission: number;
    absent: number;
  };
  subjects: SubjectGrade[];
}

interface HomeroomReportClientProps {
  className: string;
  academicYear: string;
  semesterName: string;
  homeroomTeacherName: string;
  homeroomTeacherNip: string;
  students: StudentReport[];
}

export function HomeroomReportClient({
  className,
  academicYear,
  semesterName,
  homeroomTeacherName,
  homeroomTeacherNip,
  students,
}: HomeroomReportClientProps) {
  const [selectedIndex, setSelectedIndex] = React.useState(0);
  const student = students[selectedIndex];

  if (!student) {
    return <div className="p-8 text-center text-slate-500">Tidak ada data siswa.</div>;
  }

  const handlePrint = () => {
    window.print();
  };

  return (
    <div className="space-y-6">
      {/* Control Bar (hidden on print) */}
      <div className="print:hidden">
        <Card>
          <CardContent className="p-4 flex flex-col sm:flex-row items-center justify-between gap-4">
            <div className="flex items-center gap-3 w-full sm:w-auto">
              <label className="text-xs font-semibold text-slate-700 whitespace-nowrap">
                Pilih Siswa:
              </label>
              <select
                value={selectedIndex}
                onChange={(e) => setSelectedIndex(parseInt(e.target.value))}
                className="w-full sm:w-72 bg-white border border-slate-300 rounded-lg px-3 py-2 text-xs font-medium text-slate-800 focus:outline-none focus:ring-2 focus:ring-blue-500"
              >
                {students.map((s, idx) => (
                  <option key={s.id} value={idx}>
                    {s.nis} - {s.fullName}
                  </option>
                ))}
              </select>
            </div>

            <div className="flex items-center gap-2 w-full sm:w-auto justify-end">
              <Button
                variant="outline"
                size="sm"
                disabled={selectedIndex === 0}
                onClick={() => setSelectedIndex((prev) => Math.max(0, prev - 1))}
                className="text-xs"
              >
                <ChevronLeft className="h-3.5 w-3.5 mr-1" />
                Sebelumnya
              </Button>
              <Button
                variant="outline"
                size="sm"
                disabled={selectedIndex === students.length - 1}
                onClick={() => setSelectedIndex((prev) => Math.min(students.length - 1, prev + 1))}
                className="text-xs"
              >
                Selanjutnya
                <ChevronRight className="h-3.5 w-3.5 ml-1" />
              </Button>
              <Button size="sm" onClick={handlePrint} className="text-xs bg-blue-600 hover:bg-blue-700">
                <Printer className="h-3.5 w-3.5 mr-1.5" />
                Cetak Lembar Rapor
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Official Report Card Sheet */}
      <div className="bg-white p-8 sm:p-12 shadow-sm rounded-xl border border-slate-200 print:border-none print:shadow-none print:p-0 print:m-0 text-slate-900 max-w-4xl mx-auto">
        {/* Letterhead (Kop Sekolah) */}
        <div className="flex items-center gap-4 pb-4 border-b-4 border-double border-slate-900 text-center relative">
          <div className="w-20 h-20 shrink-0 flex items-center justify-center">
            <img
              src="/images/logo-sman3oku.svg"
              alt="Logo SMAN 3 OKU"
              className="h-16 w-16 object-contain"
            />
          </div>
          <div className="flex-1">
            <h3 className="text-xs sm:text-sm font-bold tracking-wider uppercase text-slate-700">
              PEMERINTAH PROVINSI SUMATERA SELATAN
            </h3>
            <h2 className="text-xs sm:text-sm font-bold tracking-wider uppercase text-slate-800">
              DINAS PENDIDIKAN
            </h2>
            <h1 className="text-lg sm:text-xl font-extrabold uppercase tracking-widest text-slate-950 mt-0.5">
              SMA NEGERI 3 OKU
            </h1>
            <p className="text-[11px] text-slate-600 mt-1">
              Jl. Gotong Royong No. 123 Baturaja, Kabupaten Ogan Komering Ulu, Sumatera Selatan 32111
            </p>
            <p className="text-[10px] text-slate-500">
              Laman: sman3oku.sch.id | Pos-el: info@sman3oku.sch.id | Akreditasi: A
            </p>
          </div>
        </div>

        {/* Title */}
        <div className="text-center my-6">
          <h2 className="text-base sm:text-lg font-extrabold uppercase tracking-wide underline underline-offset-4">
            LAPORAN HASIL BELAJAR PESERTA DIDIK
          </h2>
          <p className="text-xs text-slate-600 mt-1 font-medium">
            (RAPOR KEMAJUAN AKADEMIK TENGAH / AKHIR SEMESTER)
          </p>
        </div>

        {/* Student Metadata Table */}
        <div className="grid grid-cols-2 gap-x-8 gap-y-1 text-xs mb-6 border border-slate-300 p-3 rounded-lg bg-slate-50/50">
          <div className="flex">
            <span className="w-32 font-semibold text-slate-600">Nama Siswa</span>
            <span className="font-bold text-slate-900">: {student.fullName}</span>
          </div>
          <div className="flex">
            <span className="w-32 font-semibold text-slate-600">Kelas</span>
            <span className="font-bold text-slate-900">: {className}</span>
          </div>
          <div className="flex">
            <span className="w-32 font-semibold text-slate-600">NIS / NISN</span>
            <span className="font-mono text-slate-900">: {student.nis} / {student.nisn}</span>
          </div>
          <div className="flex">
            <span className="w-32 font-semibold text-slate-600">Semester</span>
            <span className="font-bold text-slate-900">: {semesterName}</span>
          </div>
          <div className="flex">
            <span className="w-32 font-semibold text-slate-600">Nama Sekolah</span>
            <span className="font-medium text-slate-900">: SMAN 3 OKU</span>
          </div>
          <div className="flex">
            <span className="w-32 font-semibold text-slate-600">Tahun Ajaran</span>
            <span className="font-medium text-slate-900">: {academicYear}</span>
          </div>
        </div>

        {/* Academic Competency Table */}
        <div className="mb-6">
          <h4 className="text-xs font-bold uppercase text-slate-800 mb-2">
            A. Capaian Kompetensi Mata Pelajaran
          </h4>
          <table className="w-full text-xs border border-slate-400 border-collapse">
            <thead className="bg-slate-100 text-slate-800 font-bold border-b border-slate-400">
              <tr>
                <th className="py-2 px-2 border border-slate-400 w-10 text-center">No</th>
                <th className="py-2 px-3 border border-slate-400 text-left">Mata Pelajaran</th>
                <th className="py-2 px-2 border border-slate-400 w-14 text-center">KKTP</th>
                <th className="py-2 px-2 border border-slate-400 w-16 text-center">Nilai</th>
                <th className="py-2 px-2 border border-slate-400 w-14 text-center">Predikat</th>
                <th className="py-2 px-3 border border-slate-400 text-left">Capaian Kompetensi</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-300">
              {student.subjects.map((sub, idx) => (
                <tr key={idx}>
                  <td className="py-2 px-2 border border-slate-300 text-center">{idx + 1}</td>
                  <td className="py-2 px-3 border border-slate-300 font-semibold text-slate-900">
                    {sub.subjectName}
                    <div className="text-[10px] text-slate-500 font-normal">{sub.teacherName}</div>
                  </td>
                  <td className="py-2 px-2 border border-slate-300 text-center font-mono text-slate-600">
                    {sub.kkm}
                  </td>
                  <td className="py-2 px-2 border border-slate-300 text-center font-bold text-slate-950 font-mono">
                    {sub.score}
                  </td>
                  <td className="py-2 px-2 border border-slate-300 text-center font-bold">
                    {sub.letter}
                  </td>
                  <td className="py-2 px-3 border border-slate-300 text-[11px] leading-relaxed text-slate-700">
                    {sub.description}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Attendance and Notes Section */}
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-8">
          {/* Attendance Box */}
          <div className="border border-slate-400 p-3 rounded">
            <h4 className="text-xs font-bold uppercase text-slate-800 mb-2">
              B. Ketidakhadiran (Presensi)
            </h4>
            <table className="w-full text-xs">
              <tbody>
                <tr className="border-b border-slate-200">
                  <td className="py-1 text-slate-600">Sakit (S)</td>
                  <td className="py-1 text-right font-bold text-slate-900 font-mono">
                    {student.attendance.sick} hari
                  </td>
                </tr>
                <tr className="border-b border-slate-200">
                  <td className="py-1 text-slate-600">Izin (I)</td>
                  <td className="py-1 text-right font-bold text-slate-900 font-mono">
                    {student.attendance.permission} hari
                  </td>
                </tr>
                <tr>
                  <td className="py-1 text-slate-600">Tanpa Keterangan (A)</td>
                  <td className="py-1 text-right font-bold text-slate-900 font-mono">
                    {student.attendance.absent} hari
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          {/* Homeroom Notes Box */}
          <div className="border border-slate-400 p-3 rounded">
            <h4 className="text-xs font-bold uppercase text-slate-800 mb-2">
              C. Catatan Wali Kelas
            </h4>
            <p className="text-xs italic text-slate-700 leading-relaxed min-h-[50px]">
              "Pertahankan prestasi yang membanggakan ini. Terus tingkatkan keaktifan diskusi, budayakan
              literasi digital, serta selalu jaga kedisiplinan dan integritas sebagai peserta didik SMAN 3 OKU."
            </p>
          </div>
        </div>

        {/* Signature Area */}
        <div className="text-xs mt-10">
          <div className="text-right mb-6">
            Baturaja, {new Date().toLocaleDateString("id-ID", { day: "numeric", month: "long", year: "numeric" })}
          </div>
          <div className="grid grid-cols-3 text-center gap-4">
            <div>
              <p className="text-slate-600">Mengetahui,</p>
              <p className="font-semibold text-slate-800">Orang Tua / Wali Siswa</p>
              <div className="h-20" />
              <p className="border-t border-slate-400 mx-6 pt-1 font-semibold text-slate-800">
                ( ......................................... )
              </p>
            </div>

            <div>
              <p className="text-slate-600">Mengetahui,</p>
              <p className="font-semibold text-slate-800">Kepala SMAN 3 OKU</p>
              <div className="h-20" />
              <p className="font-bold text-slate-900 border-t border-slate-400 mx-4 pt-1">
                Drs. H. Sukardi, M.M.
              </p>
              <p className="text-[10px] text-slate-600 font-mono">
                NIP. 196803151994031002
              </p>
            </div>

            <div>
              <p className="text-slate-600">Wali Kelas,</p>
              <p className="font-semibold text-slate-800">Kelas {className}</p>
              <div className="h-20" />
              <p className="font-bold text-slate-900 border-t border-slate-400 mx-4 pt-1">
                {homeroomTeacherName}
              </p>
              <p className="text-[10px] text-slate-600 font-mono">
                NIP. {homeroomTeacherNip}
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
