"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, 
  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,
  Eye,
  EyeOff,
  KeyRound
} from "lucide-react";
import { useToast } from "@/components/ui/toast-provider";
import { Badge } from "@/components/ui/badge";

// Define the User type
interface UserApp {
  id_user: number;
  username: string;
  nip: string | null;
  role_user: 'admin' | 'ketuajurusan' | 'ketuaprodi';
  created_at: string;
  updated_at: string;
}

export default function DataTableAkun() {
  const { showSuccess, showError } = useToast();

  // State for data
  const [users, setUsers] = useState<UserApp[]>([]);
  const [filteredData, setFilteredData] = useState<UserApp[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  // State for filtering
  const [searchTerm, setSearchTerm] = useState("");
  const [roleFilter, setRoleFilter] = useState<string>("all");
  
  // State for pagination
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [paginatedData, setPaginatedData] = useState<UserApp[]>([]);
  
  // State for form
  const [formMode, setFormMode] = useState<"add" | "edit" | "reset-password">("add");
  const [formData, setFormData] = useState<Partial<UserApp & { password: string }>>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  
  // State for delete confirmation
  const [deleteId, setDeleteId] = useState<number | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);

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

  // Filter data when search term or role filter changes
  useEffect(() => {
    filterData();
  }, [searchTerm, roleFilter, users]);

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

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

  // Filter data based on search term and role
  const filterData = () => {
    let filtered = [...users];
    
    // Filter by search term
    if (searchTerm) {
      filtered = filtered.filter(
        (item) =>
          (item.username?.toLowerCase() || "").includes(searchTerm.toLowerCase()) ||
          (item.nip?.toLowerCase() || "").includes(searchTerm.toLowerCase())
      );
    }

    // Filter by role
    if (roleFilter && roleFilter !== "all") {
      filtered = filtered.filter((item) => item.role_user === roleFilter);
    }
    
    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 form data
  const resetForm = () => {
    setFormData({});
    setShowPassword(false);
  };

  // Handle form input changes
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  // Handle role select change
  const handleRoleChange = (value: string) => {
    setFormData((prev) => ({ ...prev, role_user: value as 'admin' | 'ketuajurusan' | 'ketuaprodi' }));
  };

  // Open form dialog for adding new user
  const handleAdd = () => {
    setFormMode("add");
    resetForm();
    setIsDialogOpen(true);
  };

  // Open form dialog for editing user
  const handleEdit = (data: UserApp) => {
    setFormMode("edit");
    setFormData({ ...data, password: "" }); // Don't include password in edit form initially
    setIsDialogOpen(true);
  };

  // Open form dialog for resetting password
  const handleResetPassword = (data: UserApp) => {
    setFormMode("reset-password");
    setFormData({ 
      id_user: data.id_user, 
      username: data.username, 
      nip: data.nip,
      role_user: data.role_user,
      password: "" 
    });
    setIsDialogOpen(true);
  };

  // Open delete confirmation dialog
  const handleDeleteConfirm = (id: number) => {
    setDeleteId(id);
    setIsDeleteDialogOpen(true);
  };

  // Handle form submission
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Validation
    if (formMode !== "reset-password") {
      if (!formData.username?.trim()) {
        showError("Username harus diisi");
        return;
      }
      
      if (!formData.role_user) {
        showError("Role user harus dipilih");
        return;
      }
    }

    if (formMode === "add" && !formData.password?.trim()) {
      showError("Password harus diisi untuk user baru");
      return;
    }

    if (formMode === "reset-password" && !formData.password?.trim()) {
      showError("Password baru harus diisi");
      return;
    }
    
    setIsSubmitting(true);
    
    try {
      let response;
      
      if (formMode === "add") {
        // Create new user
        response = await fetch("/api/keloladata/data-akun", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            username: formData.username?.trim(),
            nip: formData.nip?.trim() || null,
            password: formData.password,
            role_user: formData.role_user,
          }),
        });
      } else {
        // Update existing user (edit or reset password)
        const updateData: any = {
          id_user: formData.id_user,
          username: formData.username?.trim(),
          nip: formData.nip?.trim() || null,
          role_user: formData.role_user,
        };

        // Include password if it's provided
        if (formData.password?.trim()) {
          updateData.password = formData.password;
        }

        response = await fetch("/api/keloladata/data-akun", {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(updateData),
        });
      }
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to save data");
      }
      
      await fetchUsers();
      setIsDialogOpen(false);
      resetForm();
      
      if (formMode === "add") {
        showSuccess("User berhasil ditambahkan");
      } else if (formMode === "reset-password") {
        showSuccess("Password berhasil direset");
      } else {
        showSuccess("User berhasil diperbarui");
      }
    } catch (err) {
      console.error("Error saving data:", err);
      showError(err instanceof Error ? err.message : "Gagal menyimpan data");
    } finally {
      setIsSubmitting(false);
    }
  };

  // Handle delete
  const handleDelete = async () => {
    if (deleteId === null) return;
    
    setIsDeleting(true);
    
    try {
      const response = await fetch(`/api/keloladata/data-akun?id_user=${deleteId}`, {
        method: "DELETE",
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to delete user");
      }
      
      await fetchUsers();
      setIsDeleteDialogOpen(false);
      setDeleteId(null);
      showSuccess("User berhasil dihapus");
    } catch (err) {
      console.error("Error deleting data:", err);
      showError(err instanceof Error ? err.message : "Gagal menghapus user");
    } finally {
      setIsDeleting(false);
    }
  };

  // Get role badge color
  const getRoleBadgeColor = (role: string) => {
    switch (role) {
      case 'admin':
        return 'bg-red-500 hover:bg-red-600';
      case 'ketuajurusan':
        return 'bg-blue-500 hover:bg-blue-600';
      case 'ketuaprodi':
        return 'bg-green-500 hover:bg-green-600';
      default:
        return 'bg-gray-500 hover:bg-gray-600';
    }
  };

  // Get role label
  const getRoleLabel = (role: string) => {
    switch (role) {
      case 'admin':
        return 'Admin';
      case 'ketuajurusan':
        return 'Ketua Jurusan';
      case 'ketuaprodi':
        return 'Ketua Prodi';
      default:
        return role;
    }
  };

  // Calculate the range of entries being displayed
  function 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 };
  }

  // Generate pagination items
  function renderPaginationItems() {
    const totalPages = getTotalPages();
    const items = [];
    
    // Always show first page
    items.push(
      <PaginationItem key="first">
        <PaginationLink 
          isActive={currentPage === 1} 
          onClick={() => handlePageChange(1)}
          className="cursor-pointer"
        >
          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;
      items.push(
        <PaginationItem key={i}>
          <PaginationLink 
            isActive={currentPage === i} 
            onClick={() => handlePageChange(i)}
            className="cursor-pointer"
          >
            {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)}
            className="cursor-pointer"
          >
            {totalPages}
          </PaginationLink>
        </PaginationItem>
      );
    }
    
    return items;
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Loader2 className="h-8 w-8 animate-spin text-blue-500" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center text-red-500 p-4">
        {error}
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Header and Actions */}
      <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
        <div>
          <h2 className="text-2xl font-bold dark:text-white">Kelola Akun</h2>
          <p className="text-sm text-muted-foreground">
            Kelola akun pengguna sistem PODIF
          </p>
        </div>
        <Button onClick={handleAdd} className="gap-2">
          <PlusCircle className="h-4 w-4" />
          Tambah Akun
        </Button>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-2 top-2.5 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Cari username atau NIP..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-8"
          />
          {searchTerm && (
            <Button
              variant="ghost"
              size="sm"
              className="absolute right-1 top-1 h-7 w-7 p-0"
              onClick={() => setSearchTerm("")}
            >
              <X className="h-4 w-4" />
            </Button>
          )}
        </div>
        <Select value={roleFilter} onValueChange={setRoleFilter}>
          <SelectTrigger className="w-full sm:w-[200px]">
            <SelectValue placeholder="Filter Role" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">Semua Role</SelectItem>
            <SelectItem value="admin">Admin</SelectItem>
            <SelectItem value="ketuajurusan">Ketua Jurusan</SelectItem>
            <SelectItem value="ketuaprodi">Ketua Prodi</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Table Controls */}
      <div className="flex items-center gap-2">
        <span className="text-sm text-muted-foreground">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 text-muted-foreground">entries</span>
      </div>

      {/* Table */}
      <div className="border rounded-md">
        <Table>
          <TableHeader>
            <TableRow className="bg-gray-50 dark:bg-slate-800">
              <TableHead className="font-semibold text-center">No</TableHead>
              <TableHead className="font-semibold">Username</TableHead>
              <TableHead className="font-semibold">NIP</TableHead>
              <TableHead className="font-semibold text-center">Role</TableHead>
              <TableHead className="font-semibold text-center">Aksi</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {paginatedData.length === 0 ? (
              <TableRow>
                <TableCell colSpan={5} className="text-center py-8 text-muted-foreground">
                  Tidak ada data yang tersedia
                </TableCell>
              </TableRow>
            ) : (
              paginatedData.map((user, index) => (
                <TableRow 
                  key={user.id_user}
                  className={index % 2 === 0 ? "bg-white dark:bg-slate-900" : "bg-gray-50/50 dark:bg-slate-800/50"}
                >
                  <TableCell className="text-center font-medium dark:text-white">
                    {(currentPage - 1) * pageSize + index + 1}
                  </TableCell>
                  <TableCell className="font-medium dark:text-white">
                    {user.username}
                  </TableCell>
                  <TableCell className="dark:text-white">
                    {user.nip || '-'}
                  </TableCell>
                  <TableCell className="text-center">
                    <Badge className={`${getRoleBadgeColor(user.role_user)} text-white`}>
                      {getRoleLabel(user.role_user)}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-center">
                    <div className="flex items-center justify-center gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleEdit(user)}
                        className="gap-1"
                      >
                        <Pencil className="h-3 w-3" />
                        Edit
                      </Button>
                      <Button
                        variant="outline"
                        size="sm"
                        onClick={() => handleResetPassword(user)}
                        className="gap-1"
                      >
                        <KeyRound className="h-3 w-3" />
                        Reset
                      </Button>
                      <Button
                        variant="destructive"
                        size="sm"
                        onClick={() => handleDeleteConfirm(user.id_user)}
                        className="gap-1"
                      >
                        <Trash2 className="h-3 w-3" />
                        Hapus
                      </Button>
                    </div>
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </div>

      {/* Pagination */}
      {!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" : "cursor-pointer"}
                />
              </PaginationItem>
              
              {renderPaginationItems()}
              
              <PaginationItem>
                <PaginationNext 
                  onClick={() => handlePageChange(Math.min(getTotalPages(), currentPage + 1))}
                  className={currentPage === getTotalPages() ? "pointer-events-none opacity-50" : "cursor-pointer"}
                />
              </PaginationItem>
            </PaginationContent>
          </Pagination>
        </div>
      )}

      {/* Form Dialog */}
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>
              {formMode === "add" ? "Tambah Akun Baru" : formMode === "reset-password" ? "Reset Password" : "Edit Akun"}
            </DialogTitle>
          </DialogHeader>
          <form onSubmit={handleSubmit}>
            <div className="grid gap-4 py-4">
              {formMode !== "reset-password" && (
                <>
                  <div className="grid gap-2">
                    <label htmlFor="username" className="text-sm font-medium">
                      Username <span className="text-red-500">*</span>
                    </label>
                    <Input
                      id="username"
                      name="username"
                      value={formData.username || ""}
                      onChange={handleInputChange}
                      placeholder="Masukkan username"
                      required
                    />
                  </div>
                  <div className="grid gap-2">
                    <label htmlFor="nip" className="text-sm font-medium">
                      NIP (Opsional)
                    </label>
                    <Input
                      id="nip"
                      name="nip"
                      value={formData.nip || ""}
                      onChange={handleInputChange}
                      placeholder="Masukkan NIP"
                    />
                  </div>
                  <div className="grid gap-2">
                    <label htmlFor="role_user" className="text-sm font-medium">
                      Role <span className="text-red-500">*</span>
                    </label>
                    <Select
                      value={formData.role_user || ""}
                      onValueChange={handleRoleChange}
                      required
                    >
                      <SelectTrigger>
                        <SelectValue placeholder="Pilih role" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="admin">Admin</SelectItem>
                        <SelectItem value="ketuajurusan">Ketua Jurusan</SelectItem>
                        <SelectItem value="ketuaprodi">Ketua Prodi</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </>
              )}
              {formMode === "reset-password" && (
                <div className="bg-blue-50 dark:bg-blue-900/20 p-3 rounded-md">
                  <p className="text-sm text-blue-700 dark:text-blue-300">
                    Reset password untuk user: <span className="font-bold">{formData.username}</span>
                  </p>
                </div>
              )}
              {(formMode === "add" || formMode === "reset-password" || formMode === "edit") && (
                <div className="grid gap-2">
                  <label htmlFor="password" className="text-sm font-medium">
                    {formMode === "reset-password" ? "Password Baru" : "Password"} 
                    {formMode === "add" && <span className="text-red-500"> *</span>}
                    {formMode === "edit" && <span className="text-xs text-muted-foreground ml-2">(Kosongkan jika tidak ingin mengubah)</span>}
                  </label>
                  <div className="relative flex items-center">
                    <Input
                      id="password"
                      name="password"
                      type={showPassword ? "text" : "password"}
                      value={formData.password || ""}
                      onChange={handleInputChange}
                      placeholder="Masukkan password"
                      required={formMode === "add" || formMode === "reset-password"}
                      className="pr-10"
                    />
                    <Button
                      type="button"
                      variant="ghost"
                      size="sm"
                      className="absolute right-0 top-0 h-full px-3 hover:bg-transparent"
                      onClick={() => setShowPassword(!showPassword)}
                    >
                      {showPassword ? (
                        <EyeOff className="h-4 w-4" />
                      ) : (
                        <Eye className="h-4 w-4" />
                      )}
                    </Button>
                  </div>
                </div>
              )}
            </div>
            <DialogFooter>
              <DialogClose asChild>
                <Button type="button" variant="outline" disabled={isSubmitting}>
                  Batal
                </Button>
              </DialogClose>
              <Button type="submit" disabled={isSubmitting}>
                {isSubmitting ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    Menyimpan...
                  </>
                ) : (
                  "Simpan"
                )}
              </Button>
            </DialogFooter>
          </form>
        </DialogContent>
      </Dialog>

      {/* Delete Confirmation Dialog */}
      <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Konfirmasi Hapus</DialogTitle>
          </DialogHeader>
          <p className="text-sm text-muted-foreground">
            Apakah Anda yakin ingin menghapus akun ini? Tindakan ini tidak dapat dibatalkan.
          </p>
          <DialogFooter>
            <DialogClose asChild>
              <Button variant="outline" disabled={isDeleting}>
                Batal
              </Button>
            </DialogClose>
            <Button
              variant="destructive"
              onClick={handleDelete}
              disabled={isDeleting}
            >
              {isDeleting ? (
                <>
                  <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                  Menghapus...
                </>
              ) : (
                "Hapus"
              )}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}

