"use client";

import { useState, useEffect } from "react";
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 { Loader2, Settings } from "lucide-react";

interface JenisPendaftaran {
  jenis_pendaftaran: string;
}

interface EditJenisPendaftaranProps {
  onUpdateSuccess?: () => void;
}

export default function EditJenisPendaftaran({ onUpdateSuccess }: EditJenisPendaftaranProps) {
  // Toast hook

  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [jenisPendaftaranList, setJenisPendaftaranList] = useState<JenisPendaftaran[]>([]);
  const [loading, setLoading] = useState(false);
  const [updating, setUpdating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  // State for selected jenis pendaftaran and new value
  const [selectedJenisPendaftaran, setSelectedJenisPendaftaran] = useState<string>("");
  const [newValue, setNewValue] = useState<string>("");

  // Fetch jenis pendaftaran data when dialog opens
  useEffect(() => {
    if (isDialogOpen) {
      fetchJenisPendaftaran();
      resetForm();
    }
  }, [isDialogOpen]);

  // Update new value when selected jenis pendaftaran changes
  useEffect(() => {
    if (selectedJenisPendaftaran) {
      setNewValue(selectedJenisPendaftaran);
    }
  }, [selectedJenisPendaftaran]);

  // Reset form
  const resetForm = () => {
    setSelectedJenisPendaftaran("");
    setNewValue("");
    setError(null);
  };

  // Fetch unique jenis pendaftaran values
  const fetchJenisPendaftaran = async () => {
    try {
      setLoading(true);
      setError(null);
      
      const response = await fetch("/api/keloladata/setting-jenis-pendaftaran");
      
      if (!response.ok) {
        throw new Error("Failed to fetch data");
      }
      
      const data = await response.json();
      setJenisPendaftaranList(data);
    } catch (err) {
      setError("Error fetching data. Please try again later.");
      console.error("Error fetching data:", err);
    } finally {
      setLoading(false);
    }
  };

  // Handle save changes
  const handleSaveChanges = async () => {
    try {
      if (!selectedJenisPendaftaran || !newValue) {
        setError("Pilih jenis pendaftaran dan masukkan nilai baru");
        return;
      }

      if (selectedJenisPendaftaran === newValue) {
        setError("Nilai baru harus berbeda dengan nilai lama");
        return;
      }

      setUpdating(true);
      setError(null);
      
      const response = await fetch("/api/keloladata/setting-jenis-pendaftaran", {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          oldValue: selectedJenisPendaftaran,
          newValue: newValue
        }),
      });
      
      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || "Failed to update jenis pendaftaran");
      }
      
      // Reset form and notify parent component
      resetForm();
      
      // Refresh the list
      await fetchJenisPendaftaran();
      
      // Show success message
      
      // Close dialog
      setIsDialogOpen(false);
      
      // Notify parent component
      if (onUpdateSuccess) {
        onUpdateSuccess();
      }
    } catch (err) {
      setError((err as Error).message);
      console.error("Error updating jenis pendaftaran:", err);
    } finally {
      setUpdating(false);
    }
  };

  return (
    <>
      <Button 
        variant="outline" 
        onClick={() => setIsDialogOpen(true)}
        className="flex items-center gap-2"
      >
        <Settings className="h-4 w-4" />
        Edit Jenis Pendaftaran
      </Button>
      
      <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
        <DialogContent className="sm:max-w-[450px]">
          <DialogHeader>
            <DialogTitle>Edit Jenis Pendaftaran</DialogTitle>
          </DialogHeader>
          
          {loading ? (
            <div className="flex justify-center items-center py-6">
              <Loader2 className="h-6 w-6 animate-spin text-primary" />
            </div>
          ) : error ? (
            <div className="bg-destructive/10 p-3 rounded-md text-destructive text-center text-sm mb-3">
              {error}
            </div>
          ) : (
            <div className="py-2 space-y-4">
              <div className="space-y-2">
                <label htmlFor="jenis_lama" className="text-sm font-medium">
                  Jenis Lama:
                </label>
                <Select
                  value={selectedJenisPendaftaran}
                  onValueChange={setSelectedJenisPendaftaran}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Pilih jenis pendaftaran" />
                  </SelectTrigger>
                  <SelectContent>
                    {jenisPendaftaranList.map((item, index) => (
                      <SelectItem key={index} value={item.jenis_pendaftaran}>
                        {item.jenis_pendaftaran}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              
              <div className="space-y-2">
                <label htmlFor="jenis_baru" className="text-sm font-medium">
                  Jenis Baru:
                </label>
                <Input
                  id="jenis_baru"
                  value={newValue}
                  onChange={(e) => setNewValue(e.target.value)}
                  placeholder="Masukkan jenis pendaftaran baru"
                  disabled={!selectedJenisPendaftaran}
                />
              </div>
            </div>
          )}
          
          <DialogFooter className="mt-2">
            <DialogClose asChild>
              <Button type="button" variant="outline">
                Batal
              </Button>
            </DialogClose>
            <Button 
              onClick={handleSaveChanges} 
              disabled={loading || updating || !selectedJenisPendaftaran || !newValue}
            >
              {updating && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              Simpan
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
} 