"use client";

import { useEffect, useState, Suspense } from "react";
import { useParams, useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Input } from "@/components/ui/input";
import { ArrowLeft, Save, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";

interface PenilaianDetail {
  id: string;
  judul: string;
  tanggal: string;
  jenis: string;
  mapel: { namaMapel: string };
  rombel: {
    namaRombel: string;
    siswa: { id: string; nama: string; nis: string }[];
  };
  nilaiHarians: { siswaId: string; nilai: number }[];
}

export default function InputNilaiPage() {
  const params = useParams();
  const router = useRouter();
  const id = params.id as string;

  const [data, setData] = useState<PenilaianDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [scores, setScores] = useState<Record<string, number>>({});
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    fetchDetail();
  }, [id]);

  const fetchDetail = async () => {
    try {
      setLoading(true);
      const res = await fetch(`/api/guru/penilaian/${id}`);
      const json = await res.json();
      if (json.success) {
        setData(json.data);
        // Init scores
        const initialScores: Record<string, number> = {};
        json.data.nilaiHarians.forEach((n: any) => {
          initialScores[n.siswaId] = n.nilai;
        });
        setScores(initialScores);
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const handleScoreChange = (siswaId: string, val: string) => {
    const num = parseFloat(val);
    if (!isNaN(num)) {
      setScores((prev) => ({ ...prev, [siswaId]: num }));
    } else if (val === "") {
      // handle empty?
      const newScores = { ...scores };
      delete newScores[siswaId];
      setScores(newScores);
    }
  };

  const handleSave = async () => {
    setSaving(true);
    try {
      const nilaiData = Object.entries(scores).map(([siswaId, nilai]) => ({
        siswaId,
        nilai,
      }));

      const res = await fetch(`/api/guru/penilaian/${id}/nilai`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ nilaiData }),
      });

      const json = await res.json();
      if (json.success) {
        toast.success("Nilai berhasil disimpan");
        router.refresh();
      } else {
        toast.error(json.message);
      }
    } catch (error) {
      toast.error("Gagal menyimpan");
    } finally {
      setSaving(false);
    }
  };

  if (loading) return <div className="p-6">Loading...</div>;
  if (!data) return <div className="p-6">Data not found</div>;

  return (
    <div className="space-y-6 p-6">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Button variant="ghost" onClick={() => router.back()}>
            <ArrowLeft className="mr-2 h-4 w-4" /> Kembali
          </Button>
          <div>
            <h1 className="text-2xl font-bold">{data.judul}</h1>
            <div className="text-muted-foreground mt-1 flex gap-2">
              <Badge variant="outline">{data.jenis}</Badge>
              <span>{new Date(data.tanggal).toLocaleDateString("id-ID")}</span>
              <span>•</span>
              <span>{data.mapel.namaMapel}</span>
              <span>•</span>
              <span>{data.rombel.namaRombel}</span>
            </div>
          </div>
        </div>
        <Button onClick={handleSave} disabled={saving}>
          {saving ? <Loader2 className="mr-2 h-4 w-4 animate-spin" /> : <Save className="mr-2 h-4 w-4" />}
          Simpan Nilai
        </Button>
      </div>

      <Card>
        <CardContent className="p-0">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[50px]">No</TableHead>
                <TableHead>NIS</TableHead>
                <TableHead>Nama Siswa</TableHead>
                <TableHead className="w-[150px]">Nilai (0-100)</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {data.rombel.siswa.map((siswa, index) => (
                <TableRow key={siswa.id}>
                  <TableCell>{index + 1}</TableCell>
                  <TableCell>{siswa.nis}</TableCell>
                  <TableCell className="font-medium">{siswa.nama}</TableCell>
                  <TableCell>
                    <Input
                      type="number"
                      min="0"
                      max="100"
                      value={scores[siswa.id] ?? ""}
                      onChange={(e) => handleScoreChange(siswa.id, e.target.value)}
                      className="w-24"
                    />
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
