"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Loader2, Printer } from "lucide-react";
import { useSchool } from "@/hooks/use-school";

interface StudentSKL {
  id: string; // Siswa ID
  nis: string;
  nama: string;
  rombel: string;
  status: string; // From NilaiSKL or 'Belum Upload'
}

export function SklPrint() {
  const { school } = useSchool();
  const [data, setData] = useState<StudentSKL[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    // Need an endpoint to get students eligible for SKL (e.g. Kelas 12)
    // For now, let's fetch 'NilaiSKL' entries which implies readiness,
    // OR fetch all Class 12 students and join with NilaiSKL.
    // I'll assume we have an endpoint or I create a quick one /api/skl/students
    // Since I can't create too many endpoints, I'll simulate or use `api/siswa?tingkat=12` if exists.
    // I haven't created `api/siswa` filter.
    // I'll create `api/skl/students` in next step or use what I have.
    // Let's create `api/skl/students` to serve this list.

    const fetchData = async () => {
      setIsLoading(true);
      try {
        const res = await fetch("/api/skl/students");
        const result = await res.json();
        if (result.success) setData(result.data);
      } catch (e) {
        console.error(e);
      } finally {
        setIsLoading(false);
      }
    };
    fetchData();
  }, []);

  return (
    <div className="space-y-4">
      <div className="flex justify-between">
        <h3 className="text-lg font-medium">Daftar Siswa</h3>
        <Button variant="outline" onClick={() => window.location.reload()}>
          Refresh
        </Button>
      </div>

      <Table>
        <TableHeader>
          <TableRow>
            <TableHead>NIS</TableHead>
            <TableHead>Nama</TableHead>
            <TableHead>Kelas</TableHead>
            <TableHead>Status Kelulusan</TableHead>
            <TableHead className="text-right">Aksi</TableHead>
          </TableRow>
        </TableHeader>
        <TableBody>
          {isLoading ? (
            <TableRow>
              <TableCell colSpan={5} className="h-24 text-center">
                Loading...
              </TableCell>
            </TableRow>
          ) : data.length === 0 ? (
            <TableRow>
              <TableCell colSpan={5} className="text-muted-foreground h-24 text-center">
                Belum ada data siswa kelas 12 atau data nilai.
              </TableCell>
            </TableRow>
          ) : (
            data.map((item) => (
              <TableRow key={item.id}>
                <TableCell>{item.nis}</TableCell>
                <TableCell>{item.nama}</TableCell>
                <TableCell>{item.rombel}</TableCell>
                <TableCell>
                  {item.status === "LULUS" ? (
                    <span className="font-bold text-green-600">LULUS</span>
                  ) : item.status === "TIDAK LULUS" ? (
                    <span className="font-bold text-red-600">TIDAK LULUS</span>
                  ) : (
                    item.status
                  )}
                </TableCell>
                <TableCell className="text-right">
                  <Button size="sm" variant="outline" onClick={() => window.open(`/print/skl/${item.id}`, "_blank")}>
                    <Printer className="mr-2 h-4 w-4" /> Cetak
                  </Button>
                </TableCell>
              </TableRow>
            ))
          )}
        </TableBody>
      </Table>
    </div>
  );
}
