"use client";

import { useState, useEffect } from "react";
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { 
  Dialog, 
  DialogContent, 
  DialogHeader, 
  DialogTitle, 
  DialogTrigger,
  DialogFooter,
  DialogClose
} from "@/components/ui/dialog";
import { 
  Select, 
  SelectContent, 
  SelectItem, 
  SelectTrigger, 
  SelectValue 
} from "@/components/ui/select";
import {
  Pagination,
  PaginationContent,
  PaginationEllipsis,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from "@/components/ui/pagination";
import { 
  PlusCircle, 
  Pencil, 
  Trash2, 
  Search, 
  X, 
  Loader2,
  RefreshCw
} from "lucide-react";
import EditJenisPendaftaran from "@/components/datatable/edit-jenis-pendaftaran";
import UploadExcelMahasiswa from "@/components/datatable/upload-excel-mahasiswa";
import { useToast } from "@/components/ui/toast-provider";
// Define the Mahasiswa type based on API route structure
interface Mahasiswa {
  nim: string;
  nama: string;
  jk: "Pria" | "Wanita";
  agama: string | null;
  kabupaten: string | null;
  provinsi: string | null;
  jenis_pendaftaran: string | null;
  tahun_angkatan: string;
  ipk: number | null;
  id_kelompok_keahlian: number | null;
  nama_kelompok_keahlian: string | null;
  status_kuliah: "Aktif" | "Cuti" | "Lulus" | "Non-Aktif";
  semester: number;
  created_at: string;
  updated_at: string;
}

export default function DataTableMahasiswa() {
  const { showSuccess, showError } = useToast();
  // State for data
  const [mahasiswa, setMahasiswa] = useState<Mahasiswa[]>([]);
  const [filteredData, setFilteredData] = useState<Mahasiswa[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  // State for filtering
  const [searchTerm, setSearchTerm] = useState("");
  const [filterAngkatan, setFilterAngkatan] = useState<string>("");
  const [filterStatus, setFilterStatus] = useState<string>("");
  
  // State for pagination
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [paginatedData, setPaginatedData] = useState<Mahasiswa[]>([]);
  
  // State for form
  const [formMode, setFormMode] = useState<"add" | "edit">("add");
  const [formData, setFormData] = useState<Partial<Mahasiswa>>({
    jk: "Pria"
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  
  // State for delete confirmation
  const [deleteNim, setDeleteNim] = useState<string | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  
  // State for updating semester
  const [isUpdatingSemester, setIsUpdatingSemester] = useState(false);
  
  // State for jenis pendaftaran options
  const [jenisPendaftaranOptions, setJenisPendaftaranOptions] = useState<string[]>([]);
  
  // State for kelompok keahlian options
  const [kelompokKeahlianOptions, setKelompokKeahlianOptions] = useState<Array<{id_kk: number, nama_kelompok: string}>>([]);

  // Fetch data on component mount
  useEffect(() => {
    fetchMahasiswa();
    fetchJenisPendaftaranOptions();
    fetchKelompokKeahlianOptions();
  }, []);

  // Filter data when search term or filter changes
  useEffect(() => {
    filterData();
  }, [searchTerm, filterAngkatan, filterStatus, mahasiswa]);

  // Update paginated data when filtered data or pagination settings change
  useEffect(() => {
    paginateData();
  }, [filteredData, currentPage, pageSize]);

  // Fetch mahasiswa data from API
  const fetchMahasiswa = async () => {
    try {
      setLoading(true);
      const response = await fetch("/api/keloladata/data-mahasiswa");
      
      if (!response.ok) {
        throw new Error("Failed to fetch data");
      }
      
      const data = await response.json();
      setMahasiswa(data);
      setFilteredData(data);
      setError(null);
    } catch (err) {
      setError("Error fetching data. Please try again later.");
      console.error("Error fetching data:", err);
    } finally {
      setLoading(false);
    }
  };

  // Update semester for active students
  const handleUpdateSemester = async () => {
    try {
      setIsUpdatingSemester(true);
      
      const response = await fetch("/api/keloladata/update-semester", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || "Failed to update semesters");
      }

      showSuccess("Berhasil!", "Semester mahasiswa aktif berhasil diperbarui");

      // Refresh data after successful update
      await fetchMahasiswa();
    } catch (err) {
      console.error("Error updating semesters:", err);
      showError("Gagal!", (err as Error).message);
    } finally {
      setIsUpdatingSemester(false);
    }
  };

  // Filter data based on search term and filters
  const filterData = () => {
    let filtered = [...mahasiswa];
    
    // Filter by search term (NIM or name)
    if (searchTerm) {
      filtered = filtered.filter(
        (item) =>
          item.nim.toLowerCase().includes(searchTerm.toLowerCase()) ||
          item.nama.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }
    
    // Filter by angkatan
    if (filterAngkatan && filterAngkatan !== "all") {
      filtered = filtered.filter((item) => item.tahun_angkatan === filterAngkatan);
    }
    
    // Filter by status
    if (filterStatus && filterStatus !== "all") {
      filtered = filtered.filter((item) => item.status_kuliah === filterStatus);
    }
    
    setFilteredData(filtered);
    // Reset to first page when filters change
    setCurrentPage(1);
  };

  // Paginate data
  const paginateData = () => {
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    setPaginatedData(filteredData.slice(startIndex, endIndex));
  };

  // Get total number of pages
  const getTotalPages = () => {
    return Math.ceil(filteredData.length / pageSize);
  };

  // Handle page change
  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  // Handle page size change
  const handlePageSizeChange = (size: string) => {
    setPageSize(Number(size));
    setCurrentPage(1); // Reset to first page when changing page size
  };

  // Reset form data
  const resetForm = () => {
    setFormData({
      jk: "Pria",
      status_kuliah: "Aktif",
      semester: 1
    });
  };

  // Handle form input changes
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    if (name === "semester") {
      const numValue = value === "" ? 1 : parseInt(value);
      setFormData((prev) => ({ ...prev, [name]: numValue }));
    } else {
      setFormData((prev) => ({ ...prev, [name]: value }));
    }
  };

  // Handle select input changes
  const handleSelectChange = (name: string, value: string) => {
    // Handle numeric fields
    if (name === "id_kelompok_keahlian") {
      const numValue = value === "" ? null : parseInt(value);
      setFormData((prev) => ({ ...prev, [name]: numValue }));
    } else if (name === "semester") {
      const numValue = value === "" ? 1 : parseInt(value);
      setFormData((prev) => ({ ...prev, [name]: numValue }));
    } else {
      setFormData((prev) => ({ ...prev, [name]: value }));
    }
  };

  // Fetch jenis pendaftaran options
  const fetchJenisPendaftaranOptions = async () => {
    try {
      const response = await fetch("/api/keloladata/setting-jenis-pendaftaran");
      
      if (!response.ok) {
        throw new Error("Failed to fetch jenis pendaftaran options");
      }
      
      const data = await response.json();
      const options = data.map((item: any) => item.jenis_pendaftaran);
      setJenisPendaftaranOptions(options);
    } catch (err) {
      console.error("Error fetching jenis pendaftaran options:", err);
    }
  };

  // Fetch kelompok keahlian options
  const fetchKelompokKeahlianOptions = async () => {
    try {
      const response = await fetch("/api/keloladata/data-kelompok-keahlian");
      
      if (!response.ok) {
        throw new Error("Failed to fetch kelompok keahlian options");
      }
      
      const data = await response.json();
      setKelompokKeahlianOptions(data);
    } catch (err) {
      console.error("Error fetching kelompok keahlian options:", err);
    }
  };

  // Open form dialog for adding new mahasiswa
  const handleAdd = () => {
    setFormMode("add");
    resetForm();
    setIsDialogOpen(true);
    // Make sure we have the latest options
    fetchJenisPendaftaranOptions();
    fetchKelompokKeahlianOptions();
  };

  // Open form dialog for editing mahasiswa
  const handleEdit = (data: Mahasiswa) => {
    setFormMode("edit");
    setFormData(data);
    setIsDialogOpen(true);
    // Make sure we have the latest options
    fetchJenisPendaftaranOptions();
    fetchKelompokKeahlianOptions();
  };

  // Open delete confirmation dialog
  const handleDeleteConfirm = (nim: string) => {
    setDeleteNim(nim);
    setIsDeleteDialogOpen(true);
  };

  // Submit form for add/edit
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      setIsSubmitting(true);
      
      if (formMode === "add") {
        // Add new mahasiswa
        const response = await fetch("/api/keloladata/data-mahasiswa", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(formData),
        });
        
        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.message || "Failed to add mahasiswa");
        }
        showSuccess("Data mahasiswa berhasil ditambahkan!");
      } else {
        // Edit existing mahasiswa
        const response = await fetch(`/api/keloladata/data-mahasiswa?nim=${formData.nim}`, {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(formData),
        });
        
        if (!response.ok) {
          const errorData = await response.json();
          throw new Error(errorData.message || "Failed to update mahasiswa");
        }
        showSuccess("Data mahasiswa berhasil diperbarui!");
      } 
      
      // Refresh data after successful operation
      await fetchMahasiswa();
      setIsDialogOpen(false);
      resetForm();
    } catch (err) {
      console.error("Error submitting form:", err);
      showError(`Gagal ${formMode === "add" ? "menambahkan" : "memperbarui"} data mahasiswa.`);
    } finally {
      setIsSubmitting(false);
    }
  };

  // Delete mahasiswa
  const handleDelete = async () => {
    if (!deleteNim) return;
    
    try {
      setIsDeleting(true);
      
      const response = await fetch(`/api/keloladata/data-mahasiswa?nim=${deleteNim}`, {
        method: "DELETE",
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || "Failed to delete mahasiswa");
      }
      
      
      // Refresh data after successful deletion
      await fetchMahasiswa();
      setIsDeleteDialogOpen(false);
      setDeleteNim(null);
      showSuccess("Data mahasiswa berhasil dihapus!");
    } catch (err) {
      console.error("Error deleting mahasiswa:", err);
      showError("Gagal menghapus data mahasiswa.");
    } finally {
      setIsDeleting(false);
    }
  };

  // Get unique angkatan years for filter
  const getUniqueAngkatan = () => {
    const years = new Set<string>();
    mahasiswa.forEach((m) => years.add(m.tahun_angkatan));
    return Array.from(years).sort();
  };

  // Generate pagination items
  const renderPaginationItems = () => {
    const totalPages = getTotalPages();
    const items = [];
    
    // Always show first page
    items.push(
      <PaginationItem key="first">
        <PaginationLink 
          isActive={currentPage === 1} 
          onClick={() => handlePageChange(1)}
        >
          1
        </PaginationLink>
      </PaginationItem>
    );
    
    // Show ellipsis if needed
    if (currentPage > 3) {
      items.push(
        <PaginationItem key="ellipsis-start">
          <PaginationEllipsis />
        </PaginationItem>
      );
    }
    
    // Show pages around current page
    for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
      if (i === 1 || i === totalPages) continue; // Skip first and last pages as they're always shown
      items.push(
        <PaginationItem key={i}>
          <PaginationLink 
            isActive={currentPage === i} 
            onClick={() => handlePageChange(i)}
          >
            {i}
          </PaginationLink>
        </PaginationItem>
      );
    }
    
    // Show ellipsis if needed
    if (currentPage < totalPages - 2) {
      items.push(
        <PaginationItem key="ellipsis-end">
          <PaginationEllipsis />
        </PaginationItem>
      );
    }
    
    // Always show last page if there's more than one page
    if (totalPages > 1) {
      items.push(
        <PaginationItem key="last">
          <PaginationLink 
            isActive={currentPage === totalPages} 
            onClick={() => handlePageChange(totalPages)}
          >
            {totalPages}
          </PaginationLink>
        </PaginationItem>
      );
    }
    
    return items;
  };

  // Calculate the range of entries being displayed
  const getDisplayRange = () => {
    if (filteredData.length === 0) return { start: 0, end: 0 };
    
    const start = (currentPage - 1) * pageSize + 1;
    const end = Math.min(currentPage * pageSize, filteredData.length);
    
    return { start, end };
  };

  return (
    <div className="space-y-4">
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <h2 className="text-2xl font-bold">Data Mahasiswa</h2>
        <div className="flex flex-col sm:flex-row gap-2">
          <Button 
            variant="outline" 
            onClick={handleUpdateSemester}
            disabled={isUpdatingSemester}
          >
            {isUpdatingSemester ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <RefreshCw className="mr-2 h-4 w-4" />
            )}
            Update Semester Mahasiswa Aktif
          </Button>
          <Button onClick={handleAdd}>
            <PlusCircle className="mr-2 h-4 w-4" />
            Tambah Mahasiswa
          </Button>
          <EditJenisPendaftaran onUpdateSuccess={fetchMahasiswa} />
          <UploadExcelMahasiswa onUploadSuccess={fetchMahasiswa} />
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Cari berdasarkan NIM atau nama..."
            className="pl-8"
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
          {searchTerm && (
            <X
              className="absolute right-2.5 top-2.5 h-4 w-4 text-muted-foreground cursor-pointer"
              onClick={() => setSearchTerm("")}
            />
          )}
        </div>
        <Select
          value={filterAngkatan}
          onValueChange={(value) => setFilterAngkatan(value)}
        >
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Tahun Angkatan" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Semua Angkatan</SelectItem>
            {getUniqueAngkatan().map((year) => (
              <SelectItem key={year} value={year}>
                {year}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Select
          value={filterStatus}
          onValueChange={(value) => setFilterStatus(value)}
        >
          <SelectTrigger className="w-[180px]">
            <SelectValue placeholder="Status Kuliah" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Semua Status</SelectItem>
            <SelectItem value="Aktif">Aktif</SelectItem>
            <SelectItem value="Cuti">Cuti</SelectItem>
            <SelectItem value="Lulus">Lulus</SelectItem>
            <SelectItem value="Non-Aktif">Non-Aktif</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Show entries selector */}
      <div className="flex items-center gap-2">
        <span className="text-sm">Show</span>
        <Select
          value={pageSize.toString()}
          onValueChange={handlePageSizeChange}
        >
          <SelectTrigger className="w-[80px]">
            <SelectValue placeholder={pageSize.toString()} />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="5">5</SelectItem>
            <SelectItem value="10">10</SelectItem>
            <SelectItem value="25">25</SelectItem>
            <SelectItem value="50">50</SelectItem>
            <SelectItem value="100">100</SelectItem>
          </SelectContent>
        </Select>
        <span className="text-sm">entries</span>
      </div>

      {/* Table */}
      {loading ? (
        <div className="flex justify-center items-center py-8">
          <Loader2 className="h-8 w-8 animate-spin text-primary" />
        </div>
      ) : error ? (
        <div className="bg-destructive/10 p-4 rounded-md text-destructive text-center">
          {error}
        </div>
      ) : (
        <div className="border rounded-md">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead className="w-[100px]">NIM</TableHead>
                <TableHead>Nama</TableHead>
                <TableHead>Jenis Kelamin</TableHead>
                <TableHead>Agama</TableHead>
                <TableHead>Kabupaten</TableHead>
                <TableHead>Provinsi</TableHead>
                <TableHead>Jenis Pendaftaran</TableHead>
                <TableHead>Tahun Angkatan</TableHead>
                <TableHead>Semester</TableHead>
                <TableHead>IPK</TableHead>
                <TableHead>Status Kuliah</TableHead>
                <TableHead>Kelompok Keahlian</TableHead>
                <TableHead className="text-right">Aksi</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {paginatedData.length === 0 ? (
                <TableRow>
                  <TableCell colSpan={13} className="text-center py-8">
                    Tidak ada data yang sesuai dengan filter
                  </TableCell>
                </TableRow>
              ) : (
                paginatedData.map((mhs) => (
                  <TableRow key={mhs.nim}>
                    <TableCell className="font-medium">{mhs.nim}</TableCell>
                    <TableCell>{mhs.nama}</TableCell>
                    <TableCell>{mhs.jk}</TableCell>
                    <TableCell>{mhs.agama}</TableCell>
                    <TableCell>{mhs.kabupaten}</TableCell>
                    <TableCell>{mhs.provinsi}</TableCell>
                    <TableCell>{mhs.jenis_pendaftaran}</TableCell>
                    <TableCell>{mhs.tahun_angkatan}</TableCell>
                    <TableCell>{mhs.semester}</TableCell>
                    <TableCell>{mhs.ipk ? Number(mhs.ipk).toFixed(2) : "-"}</TableCell>
                    <TableCell>
                      <span
                        className={`px-2 py-1 rounded-full text-xs font-medium ${
                          mhs.status_kuliah === "Aktif"
                            ? "bg-green-100 text-green-800"
                            : mhs.status_kuliah === "Cuti"
                            ? "bg-yellow-100 text-yellow-800"
                            : mhs.status_kuliah === "Lulus"
                            ? "bg-blue-100 text-blue-800"
                            : "bg-red-100 text-red-800"
                        }`}
                      >
                        {mhs.status_kuliah}
                      </span>
                    </TableCell>
                    <TableCell>{mhs.nama_kelompok_keahlian || "-"}</TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-2">
                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleEdit(mhs)}
                        >
                          <Pencil className="h-4 w-4" />
                        </Button>
                        <Button
                          size="sm"
                          variant="outline"
                          className="text-destructive hover:bg-destructive/10"
                          onClick={() => handleDeleteConfirm(mhs.nim)}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ))
              )}
            </TableBody>
          </Table>
        </div>
      )}

      {/* Pagination info and controls */}
      {!loading && !error && filteredData.length > 0 && (
        <div className="flex flex-col sm:flex-row justify-between items-center gap-4">
          <div className="text-sm text-muted-foreground">
            Showing {getDisplayRange().start} to {getDisplayRange().end} of {filteredData.length} entries
          </div>
          <Pagination>
            <PaginationContent>
              <PaginationItem>
                <PaginationPrevious 
                  onClick={() => handlePageChange(Math.max(1, currentPage - 1))}
                  className={currentPage === 1 ? "pointer-events-none opacity-50" : ""}
                />
              </PaginationItem>
              
              {renderPaginationItems()}
              
              <PaginationItem>
                <PaginationNext 
                  onClick={() => handlePageChange(Math.min(getTotalPages(), currentPage + 1))}
                  className={currentPage === getTotalPages() ? "pointer-events-none opacity-50" : ""}
                />
              </PaginationItem>
            </PaginationContent>
          </Pagination>
        </div>
      )}

      {/* Add/Edit Dialog */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="sm:max-w-[900px] max-h-[90vh] overflow-y-auto">
          <DialogHeader>
            <DialogTitle>
              {formMode === "add" ? "Tambah Mahasiswa" : "Edit Mahasiswa"}
            </DialogTitle>
          </DialogHeader>
          <form onSubmit={handleSubmit}>
            <div className="grid gap-6 py-4">
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <div className="space-y-2">
                  <label htmlFor="nim" className="text-sm font-medium">
                    NIM <span className="text-destructive">*</span>
                  </label>
                  <Input
                    id="nim"
                    name="nim"
                    value={formData.nim || ""}
                    onChange={handleInputChange}
                    disabled={formMode === "edit"}
                    required
                    maxLength={11}
                  />
                </div>
                <div className="space-y-2">
                  <label htmlFor="nama" className="text-sm font-medium">
                    Nama <span className="text-destructive">*</span>
                  </label>
                  <Input
                    id="nama"
                    name="nama"
                    value={formData.nama || ""}
                    onChange={handleInputChange}
                    required
                  />
                </div>
                <div className="space-y-2">
                  <label htmlFor="jk" className="text-sm font-medium">
                    Jenis Kelamin <span className="text-destructive">*</span>
                  </label>
                  <Select
                    value={formData.jk || "Pria"}
                    onValueChange={(value) => handleSelectChange("jk", value)}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="Pria">Pria</SelectItem>
                      <SelectItem value="Wanita">Wanita</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <label htmlFor="agama" className="text-sm font-medium">
                    Agama
                  </label>
                  <Input
                    id="agama"
                    name="agama"
                    value={formData.agama || ""}
                    onChange={handleInputChange}
                  />
                </div>
                <div className="space-y-2">
                  <label htmlFor="kabupaten" className="text-sm font-medium">
                    Kabupaten
                  </label>
                  <Input
                    id="kabupaten"
                    name="kabupaten"
                    value={formData.kabupaten || ""}
                    onChange={handleInputChange}
                  />
                </div>
                <div className="space-y-2">
                  <label htmlFor="provinsi" className="text-sm font-medium">
                    Provinsi
                  </label>
                  <Input
                    id="provinsi"
                    name="provinsi"
                    value={formData.provinsi || ""}
                    onChange={handleInputChange}
                  />
                </div>
                <div className="space-y-2">
                  <label htmlFor="jenis_pendaftaran" className="text-sm font-medium">
                    Jenis Pendaftaran
                  </label>
                  <Input
                    id="jenis_pendaftaran"
                    name="jenis_pendaftaran"
                    value={formData.jenis_pendaftaran || ""}
                    onChange={handleInputChange}
                  />
                </div>
                <div className="space-y-2">
                  <label htmlFor="tahun_angkatan" className="text-sm font-medium">
                    Tahun Angkatan <span className="text-destructive">*</span>
                  </label>
                  <Input
                    id="tahun_angkatan"
                    name="tahun_angkatan"
                    value={formData.tahun_angkatan || ""}
                    onChange={handleInputChange}
                    required
                    maxLength={4}
                    pattern="[0-9]{4}"
                    placeholder="contoh: 2021"
                  />
                </div>
                <div className="space-y-2">
                  <label htmlFor="ipk" className="text-sm font-medium">
                    IPK
                  </label>
                  <Input
                    id="ipk"
                    name="ipk"
                    type="number"
                    step="0.01"
                    min="0"
                    max="4.00"
                    value={formData.ipk || ""}
                    onChange={handleInputChange}
                    placeholder="contoh: 3.50"
                  />
                </div>
                <div className="space-y-2">
                  <label htmlFor="id_kelompok_keahlian" className="text-sm font-medium">
                    Kelompok Keahlian
                  </label>
                  <Select
                    value={formData.id_kelompok_keahlian?.toString() || ""}
                    onValueChange={(value) => handleSelectChange("id_kelompok_keahlian", value)}
                  >
                    <SelectTrigger>
                      <SelectValue placeholder="Pilih Kelompok Keahlian" />
                    </SelectTrigger>
                    <SelectContent>
                      {kelompokKeahlianOptions.map((kelompok) => (
                        <SelectItem key={kelompok.id_kk} value={kelompok.id_kk.toString()}>
                          {kelompok.nama_kelompok}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <label htmlFor="status_kuliah" className="text-sm font-medium">
                    Status Kuliah <span className="text-destructive">*</span>
                  </label>
                  <Select
                    value={formData.status_kuliah || "Aktif"}
                    onValueChange={(value) => handleSelectChange("status_kuliah", value)}
                  >
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="Aktif">Aktif</SelectItem>
                      <SelectItem value="Cuti">Cuti</SelectItem>
                      <SelectItem value="Lulus">Lulus</SelectItem>
                      <SelectItem value="DO">DO</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                <div className="space-y-2">
                  <label htmlFor="semester" className="text-sm font-medium">
                    Semester <span className="text-destructive">*</span>
                  </label>
                  <Input
                    id="semester"
                    name="semester"
                    type="number"
                    min="1"
                    max="14"
                    value={formData.semester || ""}
                    onChange={handleInputChange}
                    required
                  />
                </div>
              </div>
            </div>
            <DialogFooter>
              <DialogClose asChild>
                <Button type="button" variant="outline">
                  Batal
                </Button>
              </DialogClose>
              <Button type="submit" disabled={isSubmitting}>
                {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                {formMode === "add" ? "Tambah" : "Simpan"}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <DialogContent className="sm:max-w-[400px]">
          <DialogHeader>
            <DialogTitle>Konfirmasi Hapus</DialogTitle>
          </DialogHeader>
          <div className="py-4">
            <p>Apakah Anda yakin ingin menghapus data mahasiswa ini?</p>
            <p className="text-sm text-muted-foreground mt-1">
              Tindakan ini tidak dapat dibatalkan.
            </p>
          </div>
          <DialogFooter>
            <DialogClose asChild>
              <Button type="button" variant="outline">
                Batal
              </Button>
            </DialogClose>
            <Button
              variant="destructive"
              onClick={handleDelete}
              disabled={isDeleting}
            >
              {isDeleting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Hapus
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
} 