import { useEffect, useState, useCallback } from "react";
import { useForm, router } from "@inertiajs/react";
import { toast } from "sonner";
import {
    UploadCloud,
    Image as ImageIcon,
    X,
    Loader2,
    Navigation,
    PlusCircle,
    Edit3,
    CheckCircle2,
    Info,
    Check,
    ChevronsUpDown,
    RotateCcw,
} from "lucide-react";

import {
    Dialog,
    DialogContent,
    DialogHeader,
    DialogTitle,
    DialogDescription,
    DialogFooter,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Checkbox } from "@/components/ui/checkbox";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from "@/components/ui/select";
import {
    Popover,
    PopoverContent,
    PopoverTrigger,
} from "@/components/ui/popover";
import {
    Command,
    CommandEmpty,
    CommandGroup,
    CommandInput,
    CommandItem,
    CommandList,
} from "@/components/ui/command";
import AreaMapPicker from "@/components/area-map-picker";
import { ConfirmDeleteDialog } from "@/components/crm/global-alertdialog";

export type OptionItem = { label: string; value: string | number };

export type FieldConfig = {
    name: string;
    longitudeName?: string;
    radiusName?: string;
    label?: string;
    type?:
        | "text"
        | "number"
        | "email"
        | "password"
        | "date"
        | "time"
        | "datetime-local"
        | "select"
        | "combobox"
        | "textarea"
        | "file"
        | "checkbox"
        | "radio"
        | "group"
        | "location";
    placeholder?: string;
    options?: OptionItem[];
    required?: boolean;
    colSpan?: 1 | 2 | 3 | 4;
    accept?: string;
    rows?: number;
    prefix?: string;
    suffix?: string;
    description?: string;
    className?: string;
    containerClassName?: string;
    children?: FieldConfig[];
};

interface DynamicFormDialogProps<T> {
    open: boolean;
    onOpenChange: (open: boolean) => void;
    title: string;
    subtitle?: string;
    endpoint: string;
    fields: FieldConfig[];
    initialValues: Record<string, any>;
    itemToEdit?: T | null;
    primaryKey?: keyof T;
    dialogSize?: "sm" | "md" | "lg" | "xl" | "2xl";
    submitText?: string;
    editText?: string;
    icon?: React.ReactNode;
}

export function DynamicFormDialog<T extends Record<string, any>>({
    open,
    onOpenChange,
    title,
    subtitle,
    endpoint,
    fields,
    initialValues,
    itemToEdit,
    primaryKey = "id" as keyof T,
    dialogSize = "lg",
    submitText = "Simpan Data",
    editText = "Perbarui Data",
    icon,
}: DynamicFormDialogProps<T>) {
    const isEdit = Boolean(itemToEdit);
    const [previews, setPreviews] = useState<Record<string, string>>({});
    const [isLocating, setIsLocating] = useState<boolean>(false);
    const [comboboxOpenStates, setComboboxOpenStates] = useState<
        Record<string, boolean>
    >({});
    const [showCloseConfirm, setShowCloseConfirm] = useState<boolean>(false);

    const { data, setData, post, processing, errors, reset, isDirty } =
        useForm(initialValues);

    const formatValue = (val: any, fieldType?: string): string => {
        if (val === null || val === undefined) return "";

        if (fieldType === "number" || typeof val === "number") {
            const num = Number(val);
            return isNaN(num) ? String(val) : Math.trunc(num).toString();
        }

        if (
            typeof val === "string" &&
            !isNaN(Number(val)) &&
            val.includes(".")
        ) {
            return val.split(".")[0];
        }

        return String(val);
    };

    const extractFieldValues = (
        fieldList: FieldConfig[],
        source: any,
        mappedData: Record<string, any>,
        initialPreviews: Record<string, string>,
    ) => {
        fieldList.forEach((field) => {
            if (field.type === "group" && field.children) {
                extractFieldValues(
                    field.children,
                    source,
                    mappedData,
                    initialPreviews,
                );
            } else {
                const val = source[field.name];

                if (field.type === "file") {
                    mappedData[field.name] = null;
                    if (typeof val === "string" && val) {
                        initialPreviews[field.name] = val.startsWith("http")
                            ? val
                            : `/storage/${val}`;
                    }
                } else if (field.type === "location") {
                    const latName = field.name;
                    const lngName = field.longitudeName || "longitude";
                    mappedData[latName] = source[latName] ?? "";
                    mappedData[lngName] = source[lngName] ?? "";
                    if (field.radiusName) {
                        mappedData[field.radiusName] =
                            source[field.radiusName] ?? "";
                    }
                } else {
                    mappedData[field.name] = formatValue(val, field.type);
                }
            }
        });
    };

    useEffect(() => {
        if (open) {
            if (itemToEdit) {
                const mappedData: Record<string, any> = {};
                const initialPreviews: Record<string, string> = {};

                extractFieldValues(
                    fields,
                    itemToEdit,
                    mappedData,
                    initialPreviews,
                );

                setData(mappedData);
                setPreviews(initialPreviews);
            } else {
                reset();
                setPreviews({});
            }
        }

        return () => {
            Object.values(previews).forEach((url) => {
                if (url.startsWith("blob:")) URL.revokeObjectURL(url);
            });
        };
    }, [itemToEdit, open]);

    const handleCloseAttempt = () => {
        if (isDirty && !processing) {
            setShowCloseConfirm(true);
        } else {
            onOpenChange(false);
        }
    };

    const handleConfirmClose = () => {
        setShowCloseConfirm(false);
        onOpenChange(false);
    };

    const handleGetCurrentLocation = (latField: string, lngField: string) => {
        if (!navigator.geolocation) {
            toast.error("Browser Anda tidak mendukung fitur Geolocation.");
            return;
        }

        setIsLocating(true);
        navigator.geolocation.getCurrentPosition(
            (position) => {
                const { latitude, longitude } = position.coords;
                setData((prev: Record<string, any>) => ({
                    ...prev,
                    [latField]: latitude.toString(),
                    [lngField]: longitude.toString(),
                }));
                setIsLocating(false);
            },
            (error) => {
                console.error("Gagal mengambil lokasi:", error);
                toast.error(
                    "Gagal mengambil lokasi saat ini. Pastikan izin GPS diizinkan di browser.",
                );
                setIsLocating(false);
            },
            { enableHighAccuracy: true },
        );
    };

    const handleFileChange = (fieldName: string, file: File | null) => {
        if (file) {
            if (previews[fieldName]?.startsWith("blob:")) {
                URL.revokeObjectURL(previews[fieldName]);
            }

            setData(fieldName, file);
            setPreviews((prev) => ({
                ...prev,
                [fieldName]: URL.createObjectURL(file),
            }));
        } else {
            if (previews[fieldName]?.startsWith("blob:")) {
                URL.revokeObjectURL(previews[fieldName]);
            }
            setData(fieldName, null as any);
            setPreviews((prev) => {
                const newPrev = { ...prev };
                delete newPrev[fieldName];
                return newPrev;
            });
        }
    };

    const submit = useCallback(() => {
        if (processing) return;

        if (isEdit && itemToEdit) {
            const itemId = itemToEdit[primaryKey];

            router.post(
                `${endpoint}/${itemId}`,
                {
                    _method: "PUT",
                    ...data,
                },
                {
                    forceFormData: true,
                    onSuccess: () => onOpenChange(false),
                },
            );
        } else {
            post(endpoint, {
                forceFormData: true,
                onSuccess: () => onOpenChange(false),
            });
        }
    }, [
        data,
        endpoint,
        isEdit,
        itemToEdit,
        primaryKey,
        processing,
        onOpenChange,
        post,
    ]);

    // Shortcut Keyboard: Ctrl + Enter / Cmd + Enter untuk Submit
    useEffect(() => {
        const handleKeyDown = (e: KeyboardEvent) => {
            if (!open) return;
            if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
                e.preventDefault();
                submit();
            }
        };

        window.addEventListener("keydown", handleKeyDown);
        return () => window.removeEventListener("keydown", handleKeyDown);
    }, [open, submit]);

    const dialogSizeClasses = {
        sm: "sm:max-w-md",
        md: "sm:max-w-lg",
        lg: "sm:max-w-2xl",
        xl: "sm:max-w-4xl",
        "2xl": "sm:max-w-6xl",
    };

    const getColSpanClass = (colSpan?: 1 | 2 | 3 | 4) => {
        switch (colSpan) {
            case 1:
                return "col-span-12 sm:col-span-3";
            case 2:
                return "col-span-12 sm:col-span-6";
            case 3:
                return "col-span-12 sm:col-span-9";
            case 4:
            default:
                return "col-span-12";
        }
    };

    const renderControl = (field: FieldConfig) => {
        if (field.type === "location") {
            const latName = field.name;
            const lngName = field.longitudeName || "longitude";
            const radiusName = field.radiusName;

            return (
                <div className="space-y-3 w-full">
                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <div className="space-y-1.5 min-w-0">
                            <Label className="text-xs text-muted-foreground font-medium">
                                Latitude
                            </Label>
                            <Input
                                type="number"
                                step="any"
                                disabled={processing}
                                value={data[latName] ?? ""}
                                onChange={(e) =>
                                    setData(latName, e.target.value)
                                }
                                placeholder="-6.200000"
                                style={{ height: "40px" }}
                                className="rounded-xl font-mono text-xs border-border h-10! text-foreground focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/10"
                            />
                            {errors[latName] && (
                                <p className="text-xs text-red-500">
                                    {errors[latName]}
                                </p>
                            )}
                        </div>
                        <div className="space-y-1.5 min-w-0">
                            <Label className="text-xs text-muted-foreground font-medium">
                                Longitude
                            </Label>
                            <Input
                                type="number"
                                step="any"
                                disabled={processing}
                                value={data[lngName] ?? ""}
                                onChange={(e) =>
                                    setData(lngName, e.target.value)
                                }
                                placeholder="106.816666"
                                style={{ height: "40px" }}
                                className="rounded-xl font-mono text-xs border-border h-10! text-foreground focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/10"
                            />
                            {errors[lngName] && (
                                <p className="text-xs text-red-500">
                                    {errors[lngName]}
                                </p>
                            )}
                        </div>
                    </div>

                    <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        disabled={isLocating || processing}
                        onClick={() =>
                            handleGetCurrentLocation(latName, lngName)
                        }
                        className="w-full rounded-xl gap-2 border-indigo-200 text-indigo-700 hover:bg-indigo-50/80 font-medium text-xs h-9 cursor-pointer"
                    >
                        {isLocating ? (
                            <Loader2 className="w-3.5 h-3.5 animate-spin" />
                        ) : (
                            <Navigation className="w-3.5 h-3.5 text-indigo-600" />
                        )}
                        {isLocating
                            ? "Mengambil Lokasi GPS..."
                            : "Gunakan Lokasi Saat Ini (GPS)"}
                    </Button>

                    <div className="rounded-2xl overflow-hidden border border-border shadow-2xs">
                        <AreaMapPicker
                            latitude={data[latName]}
                            longitude={data[lngName]}
                            radiusMeters={
                                radiusName ? data[radiusName] : undefined
                            }
                            onChange={(lat: string, lng: string) => {
                                if (processing) return;
                                setData((prev: Record<string, any>) => ({
                                    ...prev,
                                    [latName]: lat,
                                    [lngName]: lng,
                                }));
                            }}
                        />
                    </div>
                </div>
            );
        }

        if (field.type === "select") {
            return (
                <Select
                    disabled={processing}
                    value={String(data[field.name] ?? "")}
                    onValueChange={(val: string) => setData(field.name, val)}
                >
                    <SelectTrigger
                        style={{ height: "40px" }}
                        className={`w-full overflow-hidden rounded-xl border-border bg-card h-10! text-xs font-medium text-foreground focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/10 ${field.className || ""}`}
                    >
                        <span className="truncate block text-left w-full pr-2">
                            <SelectValue
                                placeholder={
                                    field.placeholder ||
                                    `-- Pilih ${field.label || ""} --`
                                }
                            />
                        </span>
                    </SelectTrigger>
                    <SelectContent className="rounded-xl border-border shadow-lg z-50">
                        {field.options?.map((opt) => (
                            <SelectItem
                                key={opt.value}
                                value={String(opt.value)}
                                className="text-xs py-2 cursor-pointer"
                            >
                                <span className="truncate block">
                                    {opt.label}
                                </span>
                            </SelectItem>
                        ))}
                    </SelectContent>
                </Select>
            );
        }

        if (field.type === "combobox") {
            const isOpen = Boolean(comboboxOpenStates[field.name]);
            const selectedOption = field.options?.find(
                (opt) => String(opt.value) === String(data[field.name]),
            );

            return (
                <Popover
                    modal={true}
                    open={isOpen}
                    onOpenChange={(openState: boolean) => {
                        if (processing) return;
                        setComboboxOpenStates((prev) => ({
                            ...prev,
                            [field.name]: openState,
                        }));
                    }}
                >
                    <PopoverTrigger asChild>
                        <Button
                            type="button"
                            variant="outline"
                            role="combobox"
                            disabled={processing}
                            aria-expanded={isOpen}
                            style={{ height: "40px" }}
                            className={`w-full justify-between rounded-xl border-border bg-card h-10! text-xs font-medium text-foreground hover:bg-muted/50 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/10 ${field.className || ""}`}
                        >
                            <span className="truncate">
                                {selectedOption
                                    ? selectedOption.label
                                    : field.placeholder ||
                                      `-- Pilih ${field.label || ""} --`}
                            </span>
                            <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                        </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[--radix-popover-trigger-width] p-0 rounded-xl border-border shadow-lg z-50">
                        <Command className="overflow-hidden">
                            <CommandInput
                                placeholder={`Cari ${field.label?.toLowerCase() || ""}...`}
                                className="text-xs h-9"
                            />
                            <CommandList className="h-60 max-h-60 overflow-y-auto overflow-x-hidden">
                                <CommandEmpty className="py-3 text-center text-xs text-muted-foreground">
                                    Data tidak ditemukan.
                                </CommandEmpty>
                                <CommandGroup>
                                    {field.options?.map((opt) => (
                                        <CommandItem
                                            key={opt.value}
                                            value={opt.label}
                                            onSelect={() => {
                                                setData(
                                                    field.name,
                                                    String(opt.value),
                                                );
                                                setComboboxOpenStates(
                                                    (prev) => ({
                                                        ...prev,
                                                        [field.name]: false,
                                                    }),
                                                );
                                            }}
                                            className="text-xs py-2 cursor-pointer"
                                        >
                                            <Check
                                                className={`mr-2 h-3.5 w-3.5 ${
                                                    String(data[field.name]) ===
                                                    String(opt.value)
                                                        ? "opacity-100 text-indigo-600"
                                                        : "opacity-0"
                                                }`}
                                            />
                                            {opt.label}
                                        </CommandItem>
                                    ))}
                                </CommandGroup>
                            </CommandList>
                        </Command>
                    </PopoverContent>
                </Popover>
            );
        }

        if (field.type === "textarea") {
            return (
                <Textarea
                    id={field.name}
                    rows={field.rows || 3}
                    disabled={processing}
                    value={data[field.name] ?? ""}
                    onChange={(e) => setData(field.name, e.target.value)}
                    placeholder={field.placeholder}
                    className={`rounded-xl border-border text-xs text-foreground focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/10 ${field.className || ""}`}
                />
            );
        }

        if (field.type === "checkbox") {
            return (
                <div
                    className={`flex items-center space-x-2.5 pt-2 ${field.className || ""}`}
                >
                    <Checkbox
                        id={field.name}
                        disabled={processing}
                        checked={Boolean(data[field.name])}
                        onCheckedChange={(checked) =>
                            setData(field.name, checked)
                        }
                        className="rounded-md border-border data-[state=checked]:bg-indigo-600"
                    />
                    <label
                        htmlFor={field.name}
                        className="text-xs font-medium text-foreground/80 cursor-pointer select-none"
                    >
                        {field.placeholder}
                    </label>
                </div>
            );
        }

        if (field.type === "radio") {
            return (
                <RadioGroup
                    value={String(data[field.name] ?? "")}
                    disabled={processing}
                    onValueChange={(val: string) => setData(field.name, val)}
                    className={`flex flex-wrap gap-4 pt-1.5 ${field.className || ""}`}
                >
                    {field.options?.map((opt) => (
                        <div
                            key={opt.value}
                            className="flex items-center space-x-2"
                        >
                            <RadioGroupItem
                                value={String(opt.value)}
                                id={`${field.name}-${opt.value}`}
                                className="text-indigo-600 border-border"
                            />
                            <Label
                                htmlFor={`${field.name}-${opt.value}`}
                                className="cursor-pointer font-medium text-xs text-foreground/80 select-none"
                            >
                                {opt.label}
                            </Label>
                        </div>
                    ))}
                </RadioGroup>
            );
        }

        if (field.type === "file") {
            const hasPreview = Boolean(previews[field.name]);

            return (
                <div className="relative w-full">
                    <label
                        htmlFor={field.name}
                        tabIndex={0}
                        onKeyDown={(e) => {
                            if (
                                (e.key === "Enter" || e.key === " ") &&
                                !processing
                            ) {
                                e.preventDefault();
                                document.getElementById(field.name)?.click();
                            }
                        }}
                        className={`group relative flex flex-col items-center justify-center w-full min-h-36 border-2 border-dashed rounded-2xl cursor-pointer transition-all overflow-hidden focus:outline-none focus:ring-2 focus:ring-indigo-500/20 ${
                            processing ? "opacity-60 cursor-not-allowed" : ""
                        } ${
                            hasPreview
                                ? "border-indigo-200 bg-indigo-50/20 hover:border-indigo-400"
                                : "border-border bg-muted/50/50 hover:bg-muted/70 hover:border-indigo-400"
                        } ${field.className || ""}`}
                    >
                        {hasPreview ? (
                            <div className="relative w-full h-36 flex items-center justify-center bg-muted">
                                <img
                                    src={previews[field.name]}
                                    alt="Preview"
                                    className="w-full h-full object-contain p-2"
                                />

                                {!processing && (
                                    <Button
                                        type="button"
                                        variant="ghost"
                                        size="icon"
                                        onClick={(e) => {
                                            e.preventDefault();
                                            e.stopPropagation();
                                            handleFileChange(field.name, null);
                                        }}
                                        className="absolute top-2 right-2 z-10 p-1.5 bg-slate-900/70 text-white rounded-full hover:bg-red-600 transition-colors shadow-md cursor-pointer"
                                        title="Hapus berkas"
                                    >
                                        <X className="w-4 h-4" />
                                    </Button>
                                )}

                                <div className="absolute inset-0 bg-slate-900/40 opacity-0 group-hover:opacity-100 flex flex-col items-center justify-center text-white text-xs font-semibold transition-opacity gap-1">
                                    <UploadCloud className="w-5 h-5" />
                                    <span>Klik untuk mengganti berkas</span>
                                </div>
                            </div>
                        ) : (
                            <div className="flex flex-col items-center justify-center py-5 px-4 text-center">
                                <div className="p-3 bg-indigo-50 text-indigo-600 rounded-2xl mb-2 group-hover:scale-105 transition-transform border border-indigo-100">
                                    <ImageIcon className="w-5 h-5" />
                                </div>
                                <p className="text-xs font-semibold text-foreground">
                                    Klik atau tarik berkas ke sini
                                </p>
                                <p className="text-[11px] text-muted-foreground/80 mt-1">
                                    Format gambar (PNG, JPG, WEBP) maks 5MB
                                </p>
                            </div>
                        )}

                        <input
                            id={field.name}
                            type="file"
                            disabled={processing}
                            accept={field.accept || "image/*"}
                            onChange={(e) =>
                                handleFileChange(
                                    field.name,
                                    e.target.files?.[0] || null,
                                )
                            }
                            className="hidden"
                        />
                    </label>
                </div>
            );
        }

        // Sanitasi Input Angka (Mencegah huruf e, +, -)
        const handleNumberKeyDown = (
            e: React.KeyboardEvent<HTMLInputElement>,
        ) => {
            if (
                field.type === "number" &&
                ["e", "E", "+", "-"].includes(e.key)
            ) {
                e.preventDefault();
            }
        };

        if (field.prefix || field.suffix) {
            return (
                <div
                    style={{ height: "40px" }}
                    className="flex h-10! items-center rounded-xl shadow-2xs border border-border overflow-hidden focus-within:ring-2 focus-within:ring-indigo-500/20 focus-within:border-indigo-500 transition-all bg-card"
                >
                    {field.prefix && (
                        <span className="inline-flex h-full items-center px-3 bg-muted/50 text-muted-foreground text-xs font-semibold border-r border-border select-none shrink-0">
                            {field.prefix}
                        </span>
                    )}
                    <Input
                        id={field.name}
                        type={field.type || "text"}
                        disabled={processing}
                        onKeyDown={handleNumberKeyDown}
                        value={formatValue(data[field.name], field.type)}
                        onChange={(e) => setData(field.name, e.target.value)}
                        placeholder={field.placeholder}
                        style={{ height: "100%" }}
                        className={`border-0 rounded-none h-full! text-xs text-foreground focus-visible:ring-0 ${field.className || ""}`}
                    />
                    {field.suffix && (
                        <span className="inline-flex h-full items-center px-3 bg-muted/50 text-muted-foreground text-xs font-semibold border-l border-border select-none shrink-0">
                            {field.suffix}
                        </span>
                    )}
                </div>
            );
        }

        return (
            <Input
                id={field.name}
                type={field.type || "text"}
                disabled={processing}
                onKeyDown={handleNumberKeyDown}
                value={formatValue(data[field.name], field.type)}
                onChange={(e) => setData(field.name, e.target.value)}
                placeholder={field.placeholder}
                style={{ height: "40px" }}
                className={`rounded-xl border-border h-10! text-xs text-foreground focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500/10 ${field.className || ""}`}
            />
        );
    };

    return (
        <>
            <Dialog open={open} onOpenChange={handleCloseAttempt}>
                <DialogContent
                    className={`${dialogSizeClasses[dialogSize]} rounded-2xl max-h-[85vh] p-0 overflow-hidden flex flex-col border-0 shadow-2xl bg-card`}
                >
                    {/* HEADER */}
                    <DialogHeader className="sticky top-0 z-20 px-6 py-4 border-b border-slate-100 bg-muted/50/90 backdrop-blur-md shadow-xs">
                        <div className="flex items-center justify-between">
                            <div className="flex items-center gap-3.5">
                                <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-2xl bg-linear-to-br from-indigo-500 to-indigo-700 text-white shadow-md shadow-indigo-500/20">
                                    {icon ? (
                                        icon
                                    ) : isEdit ? (
                                        <Edit3 className="h-5 w-5" />
                                    ) : (
                                        <PlusCircle className="h-5 w-5" />
                                    )}
                                </div>
                                <div className="space-y-0.5 text-left">
                                    <DialogTitle className="text-lg font-extrabold text-foreground tracking-tight">
                                        {isEdit
                                            ? `Edit ${title}`
                                            : `Form ${title}`}
                                    </DialogTitle>
                                    <DialogDescription className="text-xs text-muted-foreground font-medium">
                                        {subtitle
                                            ? subtitle
                                            : isEdit
                                              ? `Perbarui informasi rincian untuk data ${title.toLowerCase()} ini.`
                                              : `Lengkapi formulir di bawah untuk menambahkan ${title.toLowerCase()} baru.`}
                                    </DialogDescription>
                                </div>
                            </div>

                            {/* Tombol Reset Form (Hanya muncul saat mode Tambah) */}
                            {!isEdit && (
                                <Button
                                    type="button"
                                    variant="ghost"
                                    size="sm"
                                    disabled={processing}
                                    onClick={() => {
                                        reset();
                                        setPreviews({});
                                    }}
                                    className="text-xs text-muted-foreground hover:text-indigo-600 gap-1.5 h-8 px-2.5 rounded-lg cursor-pointer"
                                    title="Reset Form"
                                >
                                    <RotateCcw className="w-3.5 h-3.5" />
                                    <span className="hidden sm:inline">
                                        Reset
                                    </span>
                                </Button>
                            )}
                        </div>
                    </DialogHeader>

                    {/* BODY FORM */}
                    <form
                        onSubmit={(e) => {
                            e.preventDefault();
                            submit();
                        }}
                        className="flex-1 flex flex-col justify-between overflow-hidden"
                    >
                        <div className="flex-1 overflow-y-auto p-6 space-y-4">
                            <div className="grid grid-cols-12 gap-4">
                                {fields.map((field) => {
                                    if (
                                        field.type === "group" &&
                                        field.children
                                    ) {
                                        return (
                                            <div
                                                key={field.name}
                                                className={`space-y-1.5 min-w-0 ${getColSpanClass(
                                                    field.colSpan,
                                                )} ${field.containerClassName || ""}`}
                                            >
                                                {field.label && (
                                                    <Label className="text-xs font-bold text-foreground/80">
                                                        {field.label}{" "}
                                                        {field.required && (
                                                            <span className="text-red-500">
                                                                *
                                                            </span>
                                                        )}
                                                    </Label>
                                                )}
                                                <div className="flex items-start gap-3">
                                                    {field.children.map(
                                                        (child) => (
                                                            <div
                                                                key={child.name}
                                                                className={`flex-1 space-y-1.5 min-w-0 ${
                                                                    child.containerClassName ||
                                                                    ""
                                                                }`}
                                                            >
                                                                {child.label && (
                                                                    <Label
                                                                        htmlFor={
                                                                            child.name
                                                                        }
                                                                        className="text-xs font-semibold text-muted-foreground"
                                                                    >
                                                                        {
                                                                            child.label
                                                                        }{" "}
                                                                        {child.required && (
                                                                            <span className="text-red-500">
                                                                                *
                                                                            </span>
                                                                        )}
                                                                    </Label>
                                                                )}

                                                                {renderControl(
                                                                    child,
                                                                )}

                                                                {child.description && (
                                                                    <p className="text-[11px] text-muted-foreground/80 flex items-center gap-1 mt-0.5">
                                                                        <Info className="w-3 h-3 text-muted-foreground/80 shrink-0" />
                                                                        {
                                                                            child.description
                                                                        }
                                                                    </p>
                                                                )}

                                                                {errors[
                                                                    child.name
                                                                ] && (
                                                                    <p className="text-xs font-medium text-red-500 mt-1">
                                                                        {
                                                                            errors[
                                                                                child
                                                                                    .name
                                                                            ]
                                                                        }
                                                                    </p>
                                                                )}
                                                            </div>
                                                        ),
                                                    )}
                                                </div>
                                                {errors[field.name] && (
                                                    <p className="text-xs font-medium text-red-500 mt-1">
                                                        {errors[field.name]}
                                                    </p>
                                                )}
                                            </div>
                                        );
                                    }

                                    return (
                                        <div
                                            key={field.name}
                                            className={`space-y-1.5 min-w-0 ${getColSpanClass(
                                                field.colSpan,
                                            )} ${field.containerClassName || ""}`}
                                        >
                                            {field.label && (
                                                <Label
                                                    htmlFor={field.name}
                                                    className="text-xs font-bold text-foreground/80 flex items-center justify-between"
                                                >
                                                    <span>
                                                        {field.label}{" "}
                                                        {field.required && (
                                                            <span className="text-red-500">
                                                                *
                                                            </span>
                                                        )}
                                                    </span>
                                                </Label>
                                            )}

                                            {renderControl(field)}

                                            {field.description && (
                                                <p className="text-[11px] text-muted-foreground/80 flex items-center gap-1 mt-0.5">
                                                    <Info className="w-3 h-3 text-muted-foreground/80 shrink-0" />
                                                    {field.description}
                                                </p>
                                            )}

                                            {field.type !== "location" &&
                                                errors[field.name] && (
                                                    <p className="text-xs font-medium text-red-500 mt-1">
                                                        {errors[field.name]}
                                                    </p>
                                                )}
                                        </div>
                                    );
                                })}
                            </div>
                        </div>

                        {/* FOOTER */}
                        <DialogFooter className="sticky bottom-0 z-20 px-6 py-3.5 border-t border-slate-100 bg-muted/50/90 backdrop-blur-md shadow-[0_-4px_12px_rgba(0,0,0,0.04)] flex items-center justify-end gap-3 mt-auto">
                            <Button
                                type="button"
                                variant="outline"
                                disabled={processing}
                                onClick={handleCloseAttempt}
                                className="rounded-xl border-border hover:bg-muted/80 font-semibold text-xs h-10 px-5 cursor-pointer"
                            >
                                Batal
                            </Button>
                            <Button
                                type="submit"
                                disabled={processing}
                                className="rounded-xl font-bold bg-indigo-600 hover:bg-indigo-500 text-white shadow-md shadow-indigo-600/20 text-xs h-10 px-6 gap-2 cursor-pointer transition-all"
                            >
                                {processing ? (
                                    <>
                                        <Loader2 className="w-4 h-4 animate-spin" />
                                        <span>Memproses...</span>
                                    </>
                                ) : (
                                    <>
                                        <CheckCircle2 className="w-4 h-4 text-indigo-200" />
                                        <span>
                                            {isEdit ? editText : submitText}
                                        </span>
                                    </>
                                )}
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            {/* Dialog Konfirmasi Penutupan */}
            <ConfirmDeleteDialog
                open={showCloseConfirm}
                onOpenChange={setShowCloseConfirm}
                onConfirm={handleConfirmClose}
                title="Tutup Form ?"
                description="Anda memiliki perubahan yang belum disimpan. Yakin ingin menutup form ?"
                confirmText="Ya, Tutup"
            />
        </>
    );
}
