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 { router, useForm } from "@inertiajs/react";
import { useToast } from "@/hooks/use-toast";

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

interface AddHukumModalProps {
    open: boolean;
    onClose: () => void;
    onSuccess: () => void;
    hukumtype: HukumType[];
    perusahaan: { PerusahaanId: number; NamaPerusahaan: string }[];
    jenisSanksi: { JenisSanksiId: number; NamaJenisSanksi: string }[];
    penaatan: { PenaatanId: number; NamaPenaatan: string }[];
    editingData?: HukumType | null;
}

export function AddHukumModal({
    open,
    onClose,
    onSuccess,
    hukumtype,
    perusahaan,
    jenisSanksi,
    penaatan,
    editingData,
}: AddHukumModalProps) {
    const { toast } = useToast();
    const [loading, setLoading] = useState(false);

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

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

    const perusahaanOptions = perusahaan.map((p) => ({
        value: p.PerusahaanId.toString(),
        label: p.NamaPerusahaan,
    }));

    const jenisSanksiOptions = jenisSanksi.map((j) => ({
        value: j.JenisSanksiId.toString(),
        label: j.NamaJenisSanksi,
    }));

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

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

        const formData = new FormData();
        formData.append("PerusahaanId", data.PerusahaanId);
        formData.append("JenisSanksiId", data.JenisSanksiId);
        formData.append("SanksiNumber", data.SanksiNumber);
        formData.append("SanksiDate", data.SanksiDate);
        if (data.SanksiFile) formData.append("SanksiFile", data.SanksiFile);

        // Use the selected PenaatanId (no default fallback)
        formData.append("PenaatanId", data.PenaatanId);

        // Only include these fields if they have values
        if (data.PenaatanNumber)
            formData.append("PenaatanNumber", data.PenaatanNumber);
        if (data.PenaatanDate)
            formData.append("PenaatanDate", data.PenaatanDate);
        if (data.PenaatanFile)
            formData.append("PenaatanFile", data.PenaatanFile);

        const url = editingData
            ? `/admin/hukum/${editingData.HukumId}`
            : "/admin/hukum";
        const method = editingData ? post : post;

        method(url, {
            data: formData,
            forceFormData: true,
            onSuccess: () => {
                router.visit(window.location.href, { replace: true });
                toast({
                    title: "Berhasil",
                    description: editingData
                        ? "Data berhasil diperbarui"
                        : "Data berhasil ditambahkan",
                    variant: "default",
                });
                reset();
                setLoading(false);
                onSuccess();
                onClose();
            },
            onError: () => {
                toast({
                    title: "Gagal",
                    description: "Terjadi kesalahan saat menyimpan data",
                    variant: "destructive",
                });
                setLoading(false);
            },
        });
    };

    return (
        <Dialog open={open} onOpenChange={onClose}>
            <DialogContent className="max-w-4xl max-h-[90vh] overflow-y-auto">
                <DialogHeader>
                    <DialogTitle>
                        {editingData ? "Edit" : "Tambah"} Sanksi Administratif
                    </DialogTitle>
                </DialogHeader>
                <form onSubmit={handleSubmit} className="space-y-6">
                    <div className="space-y-4">
                        <Label>Nama Perusahaan</Label>
                        <Select
                            id="PerusahaanId"
                            options={perusahaanOptions}
                            placeholder="Pilih Perusahaan"
                            value={perusahaanOptions.find(
                                (p) => p.value === data.PerusahaanId
                            )}
                            onChange={(option) =>
                                setData("PerusahaanId", option?.value || "")
                            }
                        />

                        <Label>Jenis Sanksi</Label>
                        <Select
                            id="JenisSanksiId"
                            options={jenisSanksiOptions}
                            placeholder="Pilih Jenis Sanksi"
                            value={jenisSanksiOptions.find(
                                (j) => j.value === data.JenisSanksiId
                            )}
                            onChange={(option) =>
                                setData("JenisSanksiId", option?.value || "")
                            }
                        />

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

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

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

                        <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 || "");
                            }}
                            isDisabled={false} // Enable for all users
                        />
                    </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>
    );
}
