import { Button } from "@/components/ui/button";
import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogFooter,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import Select from "react-select";
import { useState, useEffect } from "react";
import { useForm } from "@inertiajs/react";
import { useToast } from "@/hooks/use-toast";

import { HukumType } from "@/types/perusahaan";

interface AddPenaatanModalProps {
    open: boolean;
    onClose: () => void;
    onSuccess: () => void;
    editingData: HukumType | null;
    penaatan: { PenaatanId: number; NamaPenaatan: string }[];
}

export function AddPenaatanModal({
    open,
    onClose,
    onSuccess,
    editingData,
    penaatan,
}: AddPenaatanModalProps) {
    const { toast } = useToast();
    const [loading, setLoading] = useState(false);

    const { data, setData, post, reset } = useForm<{
        PenaatanId: string;
        PenaatanNumber: string;
        PenaatanDate: string;
        PenaatanFile: File | null;
        currentPenaatanFile?: string;
    }>({
        PenaatanId: "",
        PenaatanNumber: "",
        PenaatanDate: "",
        PenaatanFile: null,
        currentPenaatanFile: editingData?.PenaatanFile,
    });

    const [isPenaatanModalOpen, setIsPenaatanModalOpen] = useState(false);
    const [selectedHukum, setSelectedHukum] = useState<HukumType | null>(null);

    // Handle Open Modal for Penaatan
    const handleOpenPenaatanModal = (hukum: HukumType) => {
        setSelectedHukum(hukum);
        setIsPenaatanModalOpen(true);
    };

    useEffect(() => {
        if (editingData) {
            setData({
                PenaatanId: editingData.PenaatanId?.toString() || "",
                PenaatanNumber: editingData.PenaatanNumber || "",
                PenaatanDate: editingData.PenaatanDate || "",
                PenaatanFile: null,
                currentPenaatanFile: "",
            });
        } else {
            reset();
        }
    }, [editingData, open]);

    const penaatanOptions = penaatan.map((p) => ({
        value: p.PenaatanId.toString(),
        label: p.NamaPenaatan,
    }));

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);

        const formData = new FormData();
        formData.append("PenaatanId", data.PenaatanId);
        formData.append("PenaatanNumber", data.PenaatanNumber);
        formData.append("PenaatanDate", data.PenaatanDate);
        if (data.PenaatanFile)
            formData.append("PenaatanFile", data.PenaatanFile);

        if (!editingData) return;

        post(`/admin/hukum/${editingData.HukumId}/penaatan`, {
            data: formData,
            forceFormData: true,
            onSuccess: () => {
                toast({
                    title: "Berhasil",
                    description: "Data Penaatan berhasil diperbarui",
                    variant: "default",
                });
                reset();
                setLoading(false);
                onSuccess();
                onClose();
            },
            onError: () => {
                toast({
                    title: "Gagal",
                    description: "Terjadi kesalahan saat memperbarui data",
                    variant: "destructive",
                });
                setLoading(false);
            },
        });
    };

    return (
        <Dialog open={open} onOpenChange={onClose}>
            <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
                <DialogHeader>
                    <DialogTitle>Perbarui Data Penaatan</DialogTitle>
                </DialogHeader>
                <form onSubmit={handleSubmit} className="space-y-6">
                    <div className="space-y-4">
                        <Label>Status Penaatan</Label>
                        <Select
                            id="PenaatanId"
                            options={penaatanOptions}
                            placeholder="Pilih Status Penaatan"
                            value={penaatanOptions.find(
                                (p) => p.value === data.PenaatanId
                            )}
                            onChange={(option) =>
                                setData("PenaatanId", option?.value || "")
                            }
                        />

                        <Label>Nomor SK Penaatan</Label>
                        <Input
                            value={data.PenaatanNumber}
                            onChange={(e) =>
                                setData("PenaatanNumber", e.target.value)
                            }
                        />

                        <Label>Tanggal SK Penaatan</Label>
                        <Input
                            type="date"
                            value={data.PenaatanDate}
                            onChange={(e) =>
                                setData("PenaatanDate", e.target.value)
                            }
                        />

                        <Label>Dokumen SK Penaatan</Label>
                        <div className="flex flex-col gap-2">
                            <Input
                                type="file"
                                onChange={(e) =>
                                    setData(
                                        "PenaatanFile",
                                        e.target.files
                                            ? e.target.files[0]
                                            : null
                                    )
                                }
                            />
                            {editingData?.PenaatanFile && (
                                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                                    <span>
                                        File saat ini:{" "}
                                        {editingData.PenaatanFile}
                                    </span>
                                    <Button
                                        type="button"
                                        variant="outline"
                                        size="sm"
                                        onClick={() =>
                                            window.open(
                                                `/storage/${editingData.PenaatanFile}`,
                                                "_blank"
                                            )
                                        }
                                    >
                                        Lihat File
                                    </Button>
                                </div>
                            )}
                        </div>
                    </div>

                    <DialogFooter>
                        <Button
                            type="button"
                            variant="outline"
                            onClick={onClose}
                            disabled={loading}
                        >
                            Batal
                        </Button>
                        <Button type="submit" disabled={loading}>
                            {loading ? "Menyimpan..." : "Simpan"}
                        </Button>
                    </DialogFooter>
                </form>
            </DialogContent>
        </Dialog>
    );
}
