"use client";

import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Badge } from "@/components/ui/badge";
import { Pencil, Loader2, Search, UserPlus, UserX } from "lucide-react";
import { toast } from "sonner";
import { useSchool } from "@/hooks/use-school";

interface Guru {
  id: string;
  nama: string;
  nip: string;
}

interface RombelWithWalikelas {
  id: string;
  namaRombel: string;
  tingkat: string;
  tahunPelajaran: string;
  jurusan?: {
    namaJurusan: string;
    kodeJurusan: string;
  };
  waliKelasId: string | null;
  waliKelas?: {
    nama: string;
    nip: string;
  } | null;
}

export function WalikelasManagement() {
  const { school } = useSchool();
  const [data, setData] = useState<RombelWithWalikelas[]>([]);
  const [gurus, setGurus] = useState<Guru[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedRombel, setSelectedRombel] = useState<RombelWithWalikelas | null>(null);
  const [selectedGuruId, setSelectedGuruId] = useState<string>("");
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [isSaving, setIsSaving] = useState(false);

  // Fetch Data Walikelas (Rombel)
  const fetchData = async () => {
    try {
      setIsLoading(true);
      // Construct URL with query params
      const params = new URLSearchParams();
      // Default to current school year if available, otherwise fetch all or handle in backend default
      if (school?.tahunPelajaran) {
          params.append("tahunPelajaran", school.tahunPelajaran);
      } else {
         // Fallback default logic if needed, or backend handles it
         params.append("tahunPelajaran", "2024/2025"); 
      }

      const response = await fetch(`/api/walikelas?${params.toString()}`);
      const result = await response.json();

      if (result.success) {
        setData(result.data);
      } else {
        toast.error(result.message);
      }
    } catch (error) {
      console.error("Error fetching data:", error);
      toast.error("Gagal mengambil data");
    } finally {
      setIsLoading(false);
    }
  };

  // Fetch List Guru for Dropdown
  const fetchGurus = async () => {
    try {
      const response = await fetch("/api/guru");
      const result = await response.json();

      if (result.success) {
        setGurus(result.data);
      }
    } catch (error) {
      console.error("Error fetching gurus:", error);
    }
  };

  useEffect(() => {
    fetchData();
    fetchGurus();
  }, [school?.tahunPelajaran]);

  const handleEdit = (item: RombelWithWalikelas) => {
    setSelectedRombel(item);
    setSelectedGuruId(item.waliKelasId || "unassigned");
    setIsDialogOpen(true);
  };

  const handleSave = async () => {
    if (!selectedRombel) return;

    try {
      setIsSaving(true);
      const payload = {
        rombelId: selectedRombel.id,
        guruId: selectedGuruId === "unassigned" ? null : selectedGuruId,
      };

      const response = await fetch("/api/walikelas", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      const result = await response.json();

      if (result.success) {
        toast.success("Berhasil update wali kelas");
        setIsDialogOpen(false);
        fetchData(); // Refresh data
      } else {
        toast.error(result.message);
      }
    } catch (error) {
      console.error("Error updates:", error);
      toast.error("Terjadi kesalahan saat menyimpan");
    } finally {
      setIsSaving(false);
    }
  };

  const filteredData = data.filter((item) =>
    item.namaRombel.toLowerCase().includes(searchQuery.toLowerCase()) ||
    (item.waliKelas?.nama || "").toLowerCase().includes(searchQuery.toLowerCase())
  );

  return (
    <div className="flex flex-col gap-6 p-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Data Walikelas</h1>
          <p className="text-muted-foreground">Kelola penugasan wali kelas untuk setiap rombel</p>
        </div>
      </div>

      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div className="space-y-1">
              <CardTitle>Daftar Kelas & Wali Kelas</CardTitle>
              <CardDescription>
                Tahun Pelajaran: {school?.tahunPelajaran || "2024/2025"}
              </CardDescription>
            </div>
            <div className="flex items-center gap-2">
              <div className="relative w-64">
                <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
                <Input
                  placeholder="Cari kelas atau guru..."
                  className="pl-8"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                />
              </div>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>Tingkat</TableHead>
                  <TableHead>Nama Rombel</TableHead>
                  <TableHead>Jurusan</TableHead>
                  <TableHead>Wali Kelas</TableHead>
                  <TableHead className="text-right">Aksi</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {isLoading ? (
                  <TableRow>
                    <TableCell colSpan={5} className="h-24 text-center">
                      <div className="flex items-center justify-center gap-2">
                        <Loader2 className="h-4 w-4 animate-spin" />
                        Loading data...
                      </div>
                    </TableCell>
                  </TableRow>
                ) : filteredData.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={5} className="h-24 text-center text-muted-foreground">
                      Tidak ada data kelas ditemukan.
                    </TableCell>
                  </TableRow>
                ) : (
                  filteredData.map((item) => (
                    <TableRow key={item.id}>
                      <TableCell>
                        <Badge variant="outline">{item.tingkat}</Badge>
                      </TableCell>
                      <TableCell className="font-medium">{item.namaRombel}</TableCell>
                      <TableCell>{item.jurusan?.kodeJurusan || "-"}</TableCell>
                      <TableCell>
                        {item.waliKelas ? (
                          <div className="flex items-center gap-2">
                             <div className="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10 text-primary">
                                <span className="text-xs font-semibold">
                                  {item.waliKelas.nama.substring(0, 2).toUpperCase()}
                                </span>
                             </div>
                             <div className="flex flex-col">
                               <span className="text-sm font-medium">{item.waliKelas.nama}</span>
                               <span className="text-xs text-muted-foreground">{item.waliKelas.nip || "-"}</span>
                             </div>
                          </div>
                        ) : (
                          <span className="text-muted-foreground italic text-sm">Belum ditentukan</span>
                        )}
                      </TableCell>
                      <TableCell className="text-right">
                        <Button variant="ghost" size="sm" onClick={() => handleEdit(item)}>
                          <Pencil className="mr-2 h-4 w-4" />
                          Edit
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Set Wali Kelas</DialogTitle>
            <DialogDescription>
              Pilih guru yang akan menjadi wali kelas untuk <b>{selectedRombel?.namaRombel}</b>.
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
             <div className="space-y-2">
                <label className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Pilih Guru</label>
                <Select value={selectedGuruId} onValueChange={setSelectedGuruId}>
                  <SelectTrigger>
                    <SelectValue placeholder="Pilih Guru..." />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="unassigned">
                        <div className="flex items-center text-muted-foreground">
                           <UserX className="mr-2 h-4 w-4" />
                           -- Tidak Ada / Hapus --
                        </div>
                    </SelectItem>
                    {gurus.map((guru) => (
                      <SelectItem key={guru.id} value={guru.id}>
                        {guru.nama} ({guru.nip})
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
             </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsDialogOpen(false)}>Batal</Button>
            <Button onClick={handleSave} disabled={isSaving}>
              {isSaving && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Simpan
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
