"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";

export default function SiswaNilaiPage() {
  const [data, setData] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchNilai = async () => {
      try {
        const res = await fetch("/api/siswa/nilai-harian");
        const json = await res.json();
        if (json.success) setData(json.data);
      } catch (e) {
        console.error(e);
      } finally {
        setLoading(false);
      }
    };
    fetchNilai();
  }, []);

  return (
    <div className="space-y-6 p-6">
      <h1 className="text-3xl font-bold tracking-tight">Nilai Harian</h1>
      <Card>
        <CardHeader>
          <CardTitle>Riwayat Nilai</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Tanggal</TableHead>
                <TableHead>Mapel</TableHead>
                <TableHead>Judul Penilaian</TableHead>
                <TableHead>Jenis</TableHead>
                <TableHead>Nilai</TableHead>
                <TableHead>Guru</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {loading ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center">
                    Loading...
                  </TableCell>
                </TableRow>
              ) : data.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={6} className="text-center">
                    Belum ada nilai
                  </TableCell>
                </TableRow>
              ) : (
                data.map((item: any) => (
                  <TableRow key={item.id}>
                    <TableCell>{new Date(item.penilaianHarian.tanggal).toLocaleDateString("id-ID")}</TableCell>
                    <TableCell>{item.penilaianHarian.mapel.namaMapel}</TableCell>
                    <TableCell>{item.penilaianHarian.judul}</TableCell>
                    <TableCell>
                      <Badge variant="outline">{item.penilaianHarian.jenis}</Badge>
                    </TableCell>
                    <TableCell className="text-lg font-bold">{item.nilai}</TableCell>
                    <TableCell>{item.penilaianHarian.guru.nama}</TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
