"use client";

import { useState } 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, Upload } from "lucide-react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { toast } from "sonner";
import { useJurusan } from "@/hooks/use-jurusan";
import { ImportJurusan } from "./import-jurusan";

type JurusanData = {
  id: string;
  kodeJurusan: string;
  namaJurusan: string;
  jenjang: string;
  _count?: { siswa: number };
};

const jurusanSchema = z.object({
  kodeJurusan: z.string().min(1, "Kode jurusan tidak boleh kosong"),
  namaJurusan: z.string().min(1, "Nama jurusan tidak boleh kosong"),
  jenjang: z.string().min(1, "Jenjang tidak boleh kosong"),
});

type JurusanFormData = z.infer<typeof jurusanSchema>;

export function JurusanManagement() {
  const [searchTerm, setSearchTerm] = useState("");
  const [isCreateOpen, setIsCreateOpen] = useState(false);
  const [isEditOpen, setIsEditOpen] = useState(false);
  const [isImportOpen, setIsImportOpen] = useState(false);
  const [selectedJurusan, setSelectedJurusan] = useState<JurusanData | null>(null);

  const { data: jurusan, isLoading, createJurusan, updateJurusan, deleteJurusan } = useJurusan(searchTerm);

  const createForm = useForm<JurusanFormData>({
    resolver: zodResolver(jurusanSchema),
    defaultValues: {
      kodeJurusan: "",
      namaJurusan: "",
      jenjang: "",
    },
  });

  const editForm = useForm<JurusanFormData>({
    resolver: zodResolver(jurusanSchema),
    defaultValues: {
      kodeJurusan: "",
      namaJurusan: "",
      jenjang: "",
    },
  });

  const handleCreate = async (data: JurusanFormData) => {
    try {
      await createJurusan(data);
      toast.success("Jurusan berhasil ditambahkan");
      setIsCreateOpen(false);
      createForm.reset();
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Gagal menambah jurusan");
    }
  };

  const handleEdit = (jurusan: JurusanData) => {
    setSelectedJurusan(jurusan);
    editForm.reset({
      kodeJurusan: jurusan.kodeJurusan,
      namaJurusan: jurusan.namaJurusan,
      jenjang: jurusan.jenjang,
    });
    setIsEditOpen(true);
  };

  const handleUpdate = async (data: JurusanFormData) => {
    if (!selectedJurusan) return;

    try {
      await updateJurusan(selectedJurusan.id, data);
      toast.success("Jurusan berhasil diperbarui");
      setIsEditOpen(false);
      setSelectedJurusan(null);
      editForm.reset();
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Gagal memperbarui jurusan");
    }
  };

  const handleDelete = async (jurusan: JurusanData) => {
    try {
      await deleteJurusan(jurusan.id);
      toast.success("Jurusan berhasil dihapus");
    } catch (error) {
      toast.error(error instanceof Error ? error.message : "Gagal menghapus jurusan");
    }
  };

  const getJenjangBadgeColor = (jenjang: string) => {
    switch (jenjang.toLowerCase()) {
      case "smk":
        return "bg-blue-100 text-blue-800";
      case "sma":
        return "bg-green-100 text-green-800";
      case "ma":
        return "bg-purple-100 text-purple-800";
      default:
        return "bg-gray-100 text-gray-800";
    }
  };

  if (isLoading) {
    return (
      <Card>
        <CardContent className="p-6">
          <div className="animate-pulse space-y-4">
            <div className="h-4 w-1/4 rounded bg-gray-200"></div>
            <div className="space-y-2">
              <div className="h-4 rounded bg-gray-200"></div>
              <div className="h-4 rounded bg-gray-200"></div>
              <div className="h-4 rounded bg-gray-200"></div>
            </div>
          </div>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="space-y-4">
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle>Daftar Jurusan</CardTitle>
              <CardDescription>Kelola data jurusan untuk program kejuruan sekolah</CardDescription>
            </div>
            <div className="flex space-x-2">
              <Dialog open={isImportOpen} onOpenChange={setIsImportOpen}>
                <DialogTrigger asChild>
                  <Button variant="outline">
                    <Upload className="mr-2 h-4 w-4" />
                    Import Excel
                  </Button>
                </DialogTrigger>
                <DialogContent className="max-w-md">
                  <DialogHeader>
                    <DialogTitle>Import Data Jurusan</DialogTitle>
                    <DialogDescription>Upload file Excel untuk mengimpor data jurusan</DialogDescription>
                  </DialogHeader>
                  <ImportJurusan onSuccess={() => setIsImportOpen(false)} />
                </DialogContent>
              </Dialog>

              <Dialog open={isCreateOpen} onOpenChange={setIsCreateOpen}>
                <DialogTrigger asChild>
                  <Button>
                    <Plus className="mr-2 h-4 w-4" />
                    Tambah Jurusan
                  </Button>
                </DialogTrigger>
                <DialogContent>
                  <DialogHeader>
                    <DialogTitle>Tambah Jurusan Baru</DialogTitle>
                    <DialogDescription>Masukkan informasi jurusan baru</DialogDescription>
                  </DialogHeader>
                  <Form {...createForm}>
                    <form onSubmit={createForm.handleSubmit(handleCreate)} className="space-y-4">
                      <FormField
                        control={createForm.control}
                        name="kodeJurusan"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Kode Jurusan</FormLabel>
                            <FormControl>
                              <Input placeholder="Contoh: TKJ" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={createForm.control}
                        name="namaJurusan"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Nama Jurusan</FormLabel>
                            <FormControl>
                              <Input placeholder="Contoh: Teknik Komputer dan Jaringan" {...field} />
                            </FormControl>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <FormField
                        control={createForm.control}
                        name="jenjang"
                        render={({ field }) => (
                          <FormItem>
                            <FormLabel>Jenjang</FormLabel>
                            <Select onValueChange={field.onChange} defaultValue={field.value}>
                              <FormControl>
                                <SelectTrigger>
                                  <SelectValue placeholder="Pilih jenjang" />
                                </SelectTrigger>
                              </FormControl>
                              <SelectContent>
                                <SelectItem value="SMK">SMK</SelectItem>
                                <SelectItem value="SMA">SMA</SelectItem>
                                <SelectItem value="MA">MA</SelectItem>
                              </SelectContent>
                            </Select>
                            <FormMessage />
                          </FormItem>
                        )}
                      />
                      <div className="flex justify-end space-x-2">
                        <Button type="button" variant="outline" onClick={() => setIsCreateOpen(false)}>
                          Batal
                        </Button>
                        <Button type="submit">Simpan</Button>
                      </div>
                    </form>
                  </Form>
                </DialogContent>
              </Dialog>
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="mb-4 flex items-center space-x-2">
            <div className="relative flex-1">
              <Search className="text-muted-foreground absolute top-1/2 left-2 h-4 w-4 -translate-y-1/2" />
              <Input
                placeholder="Cari berdasarkan kode atau nama jurusan..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-8"
              />
            </div>
          </div>

          <div className="rounded-md border">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>No</TableHead>
                  <TableHead>Kode Jurusan</TableHead>
                  <TableHead>Nama Jurusan</TableHead>
                  <TableHead>Jenjang</TableHead>
                  <TableHead>Jumlah Siswa</TableHead>
                  <TableHead className="text-right">Aksi</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {jurusan.length === 0 ? (
                  <TableRow>
                    <TableCell colSpan={6} className="py-8 text-center">
                      <div className="text-muted-foreground">
                        {searchTerm ? "Tidak ada jurusan yang sesuai dengan pencarian" : "Belum ada data jurusan"}
                      </div>
                    </TableCell>
                  </TableRow>
                ) : (
                  jurusan.map((item, index) => (
                    <TableRow key={item.id}>
                      <TableCell>{index + 1}</TableCell>
                      <TableCell className="font-medium">{item.kodeJurusan}</TableCell>
                      <TableCell>{item.namaJurusan}</TableCell>
                      <TableCell>
                        <Badge className={getJenjangBadgeColor(item.jenjang)}>{item.jenjang}</Badge>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-1">
                          <Users className="text-muted-foreground h-4 w-4" />
                          <span>{item._count?.siswa || 0}</span>
                        </div>
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end space-x-2">
                          <Button variant="outline" size="sm" onClick={() => handleEdit(item)}>
                            <Edit className="h-4 w-4" />
                          </Button>
                          <AlertDialog>
                            <AlertDialogTrigger asChild>
                              <Button variant="outline" size="sm" className="text-red-600 hover:text-red-700">
                                <Trash2 className="h-4 w-4" />
                              </Button>
                            </AlertDialogTrigger>
                            <AlertDialogContent>
                              <AlertDialogHeader>
                                <AlertDialogTitle>Hapus Jurusan</AlertDialogTitle>
                                <AlertDialogDescription>
                                  Apakah Anda yakin ingin menghapus jurusan &quot;{item.namaJurusan}&quot;?
                                  {item._count?.siswa && item._count.siswa > 0 && (
                                    <span className="mt-2 block font-medium text-red-600">
                                      Peringatan: Jurusan ini masih digunakan oleh {item._count.siswa} siswa dan tidak
                                      dapat dihapus.
                                    </span>
                                  )}
                                </AlertDialogDescription>
                              </AlertDialogHeader>
                              <AlertDialogFooter>
                                <AlertDialogCancel>Batal</AlertDialogCancel>
                                <AlertDialogAction
                                  onClick={() => handleDelete(item)}
                                  disabled={!!(item._count?.siswa && item._count.siswa > 0)}
                                  className="bg-red-600 hover:bg-red-700"
                                >
                                  Hapus
                                </AlertDialogAction>
                              </AlertDialogFooter>
                            </AlertDialogContent>
                          </AlertDialog>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* Edit Dialog */}
      <Dialog open={isEditOpen} onOpenChange={setIsEditOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Edit Jurusan</DialogTitle>
            <DialogDescription>Perbarui informasi jurusan</DialogDescription>
          </DialogHeader>
          <Form {...editForm}>
            <form onSubmit={editForm.handleSubmit(handleUpdate)} className="space-y-4">
              <FormField
                control={editForm.control}
                name="kodeJurusan"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Kode Jurusan</FormLabel>
                    <FormControl>
                      <Input placeholder="Contoh: TKJ" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={editForm.control}
                name="namaJurusan"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Nama Jurusan</FormLabel>
                    <FormControl>
                      <Input placeholder="Contoh: Teknik Komputer dan Jaringan" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <FormField
                control={editForm.control}
                name="jenjang"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Jenjang</FormLabel>
                    <Select onValueChange={field.onChange} defaultValue={field.value}>
                      <FormControl>
                        <SelectTrigger>
                          <SelectValue placeholder="Pilih jenjang" />
                        </SelectTrigger>
                      </FormControl>
                      <SelectContent>
                        <SelectItem value="SMK">SMK</SelectItem>
                        <SelectItem value="SMA">SMA</SelectItem>
                        <SelectItem value="MA">MA</SelectItem>
                      </SelectContent>
                    </Select>
                    <FormMessage />
                  </FormItem>
                )}
              />
              <div className="flex justify-end space-x-2">
                <Button type="button" variant="outline" onClick={() => setIsEditOpen(false)}>
                  Batal
                </Button>
                <Button type="submit">Perbarui</Button>
              </div>
            </form>
          </Form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
