"use client";

import { useState, useEffect, useCallback } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Plus, Search, Edit, Trash2, Users, Loader2, Eye, GraduationCap } from "lucide-react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { toast } from "sonner";
import { useRombel, type Rombel, type RombelFormData, type RombelFilters } from "@/hooks/use-rombel";
import { ImportRombel } from "./import-rombel";
import { RombelDetail } from "./rombel-detail";

// Types for Jurusan
interface Jurusan {
  id: string;
  kodeJurusan: string;
  namaJurusan: string;
}

// Schema validasi form
const rombelSchema = z.object({
  namaRombel: z.string().min(1, "Nama rombel tidak boleh kosong"),
  tingkat: z.string().min(1, "Tingkat tidak boleh kosong"),
  tahunPelajaran: z
    .string()
    .min(1, "Tahun pelajaran tidak boleh kosong")
    .regex(/^\d{4}\/\d{4}$/, "Format tahun pelajaran harus YYYY/YYYY"),
  jurusanId: z.string().optional(),
  isActive: z.boolean().optional(),
});

type FormValues = z.infer<typeof rombelSchema>;

// Default tingkat options untuk SMK (fallback jika belum ada data dari database)
const defaultTingkatOptions = ["10", "11", "12"];

export function RombelManagement() {
  const [searchTerm, setSearchTerm] = useState("");
  const [filterTingkat, setFilterTingkat] = useState<string>("");
  const [filterTahunPelajaran, setFilterTahunPelajaran] = useState<string>("");
  const [filterJurusanId, setFilterJurusanId] = useState<string>("");
  const [filterIsActive, setFilterIsActive] = useState<string>("");

  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const [isEditOpen, setIsEditOpen] = useState(false);
  const [isDetailOpen, setIsDetailOpen] = useState(false);
  const [selectedRombelId, setSelectedRombelId] = useState<string | null>(null);
  const [editingRombel, setEditingRombel] = useState<Rombel | null>(null);

  const [jurusanList, setJurusanList] = useState<Jurusan[]>([]);
  const [isLoadingJurusan, setIsLoadingJurusan] = useState(false);
  const [tingkatOptions, setTingkatOptions] = useState<string[]>(defaultTingkatOptions);
  const [isLoadingTingkat, setIsLoadingTingkat] = useState(false);

  const { rombel, isLoading, error, fetchRombel, createRombel, updateRombel, deleteRombel } = useRombel();

  // Form untuk create
  const createForm = useForm<FormValues>({
    resolver: zodResolver(rombelSchema),
    defaultValues: {
      namaRombel: "",
      tingkat: "",
      tahunPelajaran: "",
      jurusanId: "",
      isActive: true,
    },
  });

  // Form untuk edit
  const editForm = useForm<FormValues>({
    resolver: zodResolver(rombelSchema),
    defaultValues: {
      namaRombel: "",
      tingkat: "",
      tahunPelajaran: "",
      jurusanId: "",
      isActive: true,
    },
  });

  // Fetch jurusan list
  const fetchJurusan = useCallback(async () => {
    setIsLoadingJurusan(true);
    try {
      const token = localStorage.getItem("token");
      const response = await fetch("/api/jurusan", {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      const data = await response.json();
      if (data.success) {
        setJurusanList(data.data);
      }
    } catch {
      console.error("Error fetching jurusan");
    } finally {
      setIsLoadingJurusan(false);
    }
  }, []);

  // Fetch tingkat list from database
  const fetchTingkat = useCallback(async () => {
    setIsLoadingTingkat(true);
    try {
      const token = localStorage.getItem("token");
      const response = await fetch("/api/rombel/tingkat", {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      const data = await response.json();
      if (data.success && data.data.length > 0) {
        setTingkatOptions(data.data);
      }
      // Jika tidak ada data, tetap gunakan defaultTingkatOptions
    } catch {
      console.error("Error fetching tingkat");
    } finally {
      setIsLoadingTingkat(false);
    }
  }, []);

  // Fetch rombel dengan filters
  const handleFetch = useCallback(() => {
    const filters: RombelFilters = {};
    if (searchTerm) filters.search = searchTerm;
    if (filterTingkat && filterTingkat !== "all") filters.tingkat = filterTingkat;
    if (filterTahunPelajaran && filterTahunPelajaran !== "all") filters.tahunPelajaran = filterTahunPelajaran;
    if (filterJurusanId && filterJurusanId !== "all") filters.jurusanId = filterJurusanId;
    if (filterIsActive && filterIsActive !== "all") filters.isActive = filterIsActive;
    fetchRombel(filters);
  }, [searchTerm, filterTingkat, filterTahunPelajaran, filterJurusanId, filterIsActive, fetchRombel]);

  useEffect(() => {
    fetchJurusan();
    fetchTingkat();
  }, [fetchJurusan, fetchTingkat]);

  useEffect(() => {
    handleFetch();
  }, [handleFetch]);

  // Handle create
  const handleCreate = async (data: FormValues) => {
    const formData: RombelFormData = {
      namaRombel: data.namaRombel,
      tingkat: data.tingkat,
      tahunPelajaran: data.tahunPelajaran,
      jurusanId: data.jurusanId || null,
      isActive: data.isActive ?? true,
    };

    const result = await createRombel(formData);
    if (result) {
      toast.success("Rombel berhasil ditambahkan");
      setIsCreateOpen(false);
      createForm.reset();
      handleFetch();
    } else {
      toast.error(error || "Gagal menambah rombel");
    }
  };

  // Handle edit
  const handleEditClick = (item: Rombel) => {
    setEditingRombel(item);
    editForm.reset({
      namaRombel: item.namaRombel,
      tingkat: item.tingkat,
      tahunPelajaran: item.tahunPelajaran,
      jurusanId: item.jurusanId || "",
      isActive: item.isActive,
    });
    setIsEditOpen(true);
  };

  const handleUpdate = async (data: FormValues) => {
    if (!editingRombel) return;

    const formData: Partial<RombelFormData> = {
      namaRombel: data.namaRombel,
      tingkat: data.tingkat,
      tahunPelajaran: data.tahunPelajaran,
      jurusanId: data.jurusanId || null,
      isActive: data.isActive,
    };

    const result = await updateRombel(editingRombel.id, formData);
    if (result) {
      toast.success("Rombel berhasil diperbarui");
      setIsEditOpen(false);
      setEditingRombel(null);
      editForm.reset();
      handleFetch();
    } else {
      toast.error(error || "Gagal memperbarui rombel");
    }
  };

  // Handle delete
  const handleDelete = async (id: string, namaRombel: string) => {
    const success = await deleteRombel(id);
    if (success) {
      toast.success(`Rombel "${namaRombel}" berhasil dihapus`);
      handleFetch();
    } else {
      toast.error(error || "Gagal menghapus rombel");
    }
  };

  // Handle view detail
  const handleViewDetail = (id: string) => {
    setSelectedRombelId(id);
    setIsDetailOpen(true);
  };

  // Get unique tahun pelajaran from data
  const uniqueTahunPelajaran = [...new Set(rombel.map((r) => r.tahunPelajaran))].sort().reverse();

  // Render form content
  const renderFormContent = (form: typeof createForm, onSubmit: (data: FormValues) => void, isEdit: boolean) => (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
        <FormField
          control={form.control}
          name="namaRombel"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Nama Rombel</FormLabel>
              <FormControl>
                <Input placeholder="Contoh: X RPL 1" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="tingkat"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Tingkat</FormLabel>
              <Select onValueChange={field.onChange} value={field.value}>
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder="Pilih tingkat" />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  {isLoadingTingkat ? (
                    <SelectItem value="loading" disabled>
                      Loading...
                    </SelectItem>
                  ) : (
                    tingkatOptions.map((tingkat) => (
                      <SelectItem key={tingkat} value={tingkat}>
                        {tingkat}
                      </SelectItem>
                    ))
                  )}
                </SelectContent>
              </Select>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="tahunPelajaran"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Tahun Pelajaran</FormLabel>
              <FormControl>
                <Input placeholder="Contoh: 2024/2025" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />

        <FormField
          control={form.control}
          name="jurusanId"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Jurusan (Opsional)</FormLabel>
              <Select
                onValueChange={(value) => field.onChange(value === "none" ? "" : value)}
                value={field.value || "none"}
              >
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder="Pilih jurusan" />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  <SelectItem value="none">Tidak Ada Jurusan</SelectItem>
                  {isLoadingJurusan ? (
                    <SelectItem value="loading" disabled>
                      Loading...
                    </SelectItem>
                  ) : (
                    jurusanList.map((jurusan) => (
                      <SelectItem key={jurusan.id} value={jurusan.id}>
                        {jurusan.kodeJurusan} - {jurusan.namaJurusan}
                      </SelectItem>
                    ))
                  )}
                </SelectContent>
              </Select>
              <FormMessage />
            </FormItem>
          )}
        />

        {isEdit && (
          <FormField
            control={form.control}
            name="isActive"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Status</FormLabel>
                <Select onValueChange={(value) => field.onChange(value === "true")} value={String(field.value)}>
                  <FormControl>
                    <SelectTrigger>
                      <SelectValue placeholder="Pilih status" />
                    </SelectTrigger>
                  </FormControl>
                  <SelectContent>
                    <SelectItem value="true">Aktif</SelectItem>
                    <SelectItem value="false">Tidak Aktif</SelectItem>
                  </SelectContent>
                </Select>
                <FormMessage />
              </FormItem>
            )}
          />
        )}

        <div className="flex justify-end space-x-2 pt-4">
          <Button
            type="button"
            variant="outline"
            onClick={() => (isEdit ? setIsEditOpen(false) : setIsCreateOpen(false))}
          >
            Batal
          </Button>
          <Button type="submit" disabled={isLoading}>
            {isLoading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
            {isEdit ? "Perbarui" : "Simpan"}
          </Button>
        </div>
      </form>
    </Form>
  );

  if (isLoading && rombel.length === 0) {
    return (
      <Card>
        <CardContent className="flex items-center justify-center py-10">
          <Loader2 className="h-8 w-8 animate-spin" />
        </CardContent>
      </Card>
    );
  }

  return (
    <>
      <Card>
        <CardHeader>
          <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <GraduationCap className="h-5 w-5" />
                Data Rombongan Belajar
              </CardTitle>
              <CardDescription>Kelola data rombel dan kelas siswa</CardDescription>
            </div>
            <div className="flex flex-wrap gap-2">
              <ImportRombel onImportComplete={handleFetch} />

              <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
                <DialogTrigger asChild>
                  <Button onClick={() => createForm.reset()}>
                    <Plus className="mr-2 h-4 w-4" />
                    Tambah Rombel
                  </Button>
                </DialogTrigger>
                <DialogContent className="max-w-md">
                  <DialogHeader>
                    <DialogTitle>Tambah Rombel Baru</DialogTitle>
                    <DialogDescription>Tambahkan rombongan belajar baru ke sistem</DialogDescription>
                  </DialogHeader>
                  {renderFormContent(createForm, handleCreate, false)}
                </DialogContent>
              </Dialog>
            </div>
          </div>

          {/* Filters */}
          <div className="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-5">
            <div className="relative">
              <Search className="text-muted-foreground absolute top-2.5 left-2 h-4 w-4" />
              <Input
                placeholder="Cari rombel..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-8"
              />
            </div>

            <Select value={filterTingkat} onValueChange={setFilterTingkat}>
              <SelectTrigger>
                <SelectValue placeholder="Filter Tingkat" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Semua Tingkat</SelectItem>
                {tingkatOptions.map((tingkat) => (
                  <SelectItem key={tingkat} value={tingkat}>
                    Tingkat {tingkat}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select value={filterTahunPelajaran} onValueChange={setFilterTahunPelajaran}>
              <SelectTrigger>
                <SelectValue placeholder="Tahun Pelajaran" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Semua Tahun</SelectItem>
                {uniqueTahunPelajaran.map((tahun) => (
                  <SelectItem key={tahun} value={tahun}>
                    {tahun}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select value={filterJurusanId} onValueChange={setFilterJurusanId}>
              <SelectTrigger>
                <SelectValue placeholder="Filter Jurusan" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Semua Jurusan</SelectItem>
                {jurusanList.map((jurusan) => (
                  <SelectItem key={jurusan.id} value={jurusan.id}>
                    {jurusan.kodeJurusan}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>

            <Select value={filterIsActive} onValueChange={setFilterIsActive}>
              <SelectTrigger>
                <SelectValue placeholder="Filter Status" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">Semua Status</SelectItem>
                <SelectItem value="true">Aktif</SelectItem>
                <SelectItem value="false">Tidak Aktif</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardHeader>

        <CardContent>
          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-12">No</TableHead>
                  <TableHead>Nama Rombel</TableHead>
                  <TableHead>Tingkat</TableHead>
                  <TableHead>Tahun Pelajaran</TableHead>
                  <TableHead>Jurusan</TableHead>
                  <TableHead className="text-center">Jumlah Siswa</TableHead>
                  <TableHead>Status</TableHead>
                  <TableHead className="text-right">Aksi</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {rombel.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={8} className="h-24 text-center">
                      {searchTerm || filterTingkat || filterTahunPelajaran || filterJurusanId || filterIsActive
                        ? "Tidak ditemukan rombel yang cocok"
                        : "Belum ada data rombel"}
                    </TableCell>
                  </TableRow>
                ) : (
                  rombel.map((item, index) => (
                    <TableRow key={item.id}>
                      <TableCell className="font-medium">{index + 1}</TableCell>
                      <TableCell className="font-semibold">{item.namaRombel}</TableCell>
                      <TableCell>
                        <Badge variant="outline">Tingkat {item.tingkat}</Badge>
                      </TableCell>
                      <TableCell>{item.tahunPelajaran}</TableCell>
                      <TableCell>{item.jurusan ? `${item.jurusan.kodeJurusan}` : "-"}</TableCell>
                      <TableCell className="text-center">
                        <div className="flex items-center justify-center gap-1">
                          <Users className="text-muted-foreground h-4 w-4" />
                          <span>{item._count?.siswa || 0}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <Badge variant={item.isActive ? "default" : "secondary"}>
                          {item.isActive ? "Aktif" : "Tidak Aktif"}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end space-x-1">
                          <Button variant="ghost" size="icon" onClick={() => handleViewDetail(item.id)} title="Detail">
                            <Eye className="h-4 w-4" />
                          </Button>
                          <Button variant="ghost" size="icon" onClick={() => handleEditClick(item)} title="Edit">
                            <Edit className="h-4 w-4" />
                          </Button>
                          <AlertDialog>
                            <AlertDialogTrigger asChild>
                              <Button variant="ghost" size="icon" className="text-destructive" title="Hapus">
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            </AlertDialogTrigger>
                            <AlertDialogContent>
                              <AlertDialogHeader>
                                <AlertDialogTitle>Hapus Rombel?</AlertDialogTitle>
                                <AlertDialogDescription>
                                  Apakah Anda yakin ingin menghapus rombel &quot;{item.namaRombel}&quot;? Tindakan ini
                                  tidak dapat dibatalkan.
                                </AlertDialogDescription>
                              </AlertDialogHeader>
                              <AlertDialogFooter>
                                <AlertDialogCancel>Batal</AlertDialogCancel>
                                <AlertDialogAction
                                  className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                                  onClick={() => handleDelete(item.id, item.namaRombel)}
                                >
                                  Hapus
                                </AlertDialogAction>
                              </AlertDialogFooter>
                            </AlertDialogContent>
                          </AlertDialog>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* Edit Dialog */}
      <Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Edit Rombel</DialogTitle>
            <DialogDescription>Perbarui data rombongan belajar</DialogDescription>
          </DialogHeader>
          {renderFormContent(editForm, handleUpdate, true)}
        </DialogContent>
      </Dialog>

      {/* Detail Dialog */}
      <RombelDetail rombelId={selectedRombelId} open={isDetailOpen} onOpenChange={setIsDetailOpen} />
    </>
  );
}
