import { useState, useEffect } from 'react';
import { Head, router } from '@inertiajs/react';
import { FlaskConical } from 'lucide-react';
import AppLayout from '@/layouts/app-layout';
import { ResizableDrawer } from '@/components/common/ResizableDrawer';
import { DeleteConfirmationDialog } from '@/components/common/DeleteConfirmationDialog';
import { SampleTypeForm } from '../sample-type/components/SampleTypeForm';
import { RegulationRelationManager } from './components/RegulationRelationManager';
import {
    SampleType,
    Regulation,
    RegulationAttachment,
    AttachmentParameterStandard,
    Parameter,
    SampleTypeCategory,
    LhuFormat,
    Unit,
    Method,
} from '../types';
import { SampleTypeList, RegulationList, AttachmentList, ParameterList } from './components/MasterLists';
import { RegulationForm } from '../regulation/components/RegulationForm';
import { ParameterBakuMutuForm } from './components/ParameterBakuMutuForm';
import { AttachmentForm } from './components/AttachmentForm';
import axios from 'axios';
import { toast } from 'sonner';

interface Props {
    sampleTypes: { data: SampleType[] };
    regulations: { data: Regulation[] };
    parameterCategories?: { data: any[] };
    subcontractLabs?: { data: any[] };
    sampleTypeCategories: { data: SampleTypeCategory[] };
    lhuFormats: { data: LhuFormat[] };
    units: { data: Unit[] };
    methods: { data: Method[] };
}

export default function LimsMasterIndex({
    sampleTypes,
    regulations,
    sampleTypeCategories,
    lhuFormats,
    units,
    methods,
}: Props) {
    // Selection state
    const [selectedSampleType, setSelectedSampleType] = useState<SampleType | null>(null);
    const [selectedRegulation, setSelectedRegulation] = useState<Regulation | null>(null);
    const [selectedAttachment, setSelectedAttachment] = useState<RegulationAttachment | null>(null);

    // Filtered data based on selection
    const [filteredRegulations, setFilteredRegulations] = useState<Regulation[]>([]);
    const [filteredAttachments, setFilteredAttachments] = useState<RegulationAttachment[]>([]);
    const [filteredParameters, setFilteredParameters] = useState<AttachmentParameterStandard[]>([]);

    // Loading states
    const [isLoadingRegulations, setIsLoadingRegulations] = useState(false);
    const [isLoadingAttachments, setIsLoadingAttachments] = useState(false);
    const [isLoadingParameters, setIsLoadingParameters] = useState(false);

    // Available parameters for dropdown (all parameters)
    const [availableParameters, setAvailableParameters] = useState<Parameter[]>([]);

    // Drawer states
    const [isRelationDrawerOpen, setIsRelationDrawerOpen] = useState(false);
    const [isSampleTypeDrawerOpen, setIsSampleTypeDrawerOpen] = useState(false);
    const [isRegulationDrawerOpen, setIsRegulationDrawerOpen] = useState(false);
    const [isAttachmentDrawerOpen, setIsAttachmentDrawerOpen] = useState(false);
    const [isParameterDrawerOpen, setIsParameterDrawerOpen] = useState(false);
    const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
    const [deleteTarget, setDeleteTarget] = useState<'sample-type' | 'regulation' | 'attachment' | 'parameter'>('parameter');

    // Form states
    const [selectedSampleTypeForEdit, setSelectedSampleTypeForEdit] = useState<SampleType | null>(null);
    const [selectedRegulationForEdit, setSelectedRegulationForEdit] = useState<Regulation | null>(null);
    const [selectedAttachmentForEdit, setSelectedAttachmentForEdit] = useState<RegulationAttachment | null>(null);
    const [selectedParameter, setSelectedParameter] = useState<AttachmentParameterStandard | null>(null);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isDeleting, setIsDeleting] = useState(false);

    // Regulation relation state
    const [selectedRegulationIds, setSelectedRegulationIds] = useState<number[]>([]);

    // Fetch regulations when sample type changes
    useEffect(() => {
        if (selectedSampleType) {
            fetchRegulationsForSampleType(selectedSampleType.id);
        } else {
            setFilteredRegulations([]);
        }
        setSelectedRegulation(null);
        setSelectedAttachment(null);
        setFilteredAttachments([]);
        setFilteredParameters([]);
    }, [selectedSampleType]);

    // Fetch attachments when regulation changes
    useEffect(() => {
        if (selectedRegulation) {
            fetchAttachmentsForRegulation(selectedRegulation.id);
        } else {
            setFilteredAttachments([]);
        }
        setSelectedAttachment(null);
        setFilteredParameters([]);
    }, [selectedRegulation]);

    // Fetch parameters when attachment changes
    useEffect(() => {
        if (selectedAttachment) {
            fetchParametersForAttachment(selectedAttachment.id);
        } else {
            setFilteredParameters([]);
        }
    }, [selectedAttachment]);

    // Fetch all parameters on mount for the form dropdown
    useEffect(() => {
        fetchAllParameters();
    }, []);

    const fetchAllParameters = async () => {
        try {
            const response = await axios.get('/operation/parameter/list');
            setAvailableParameters(response.data.data || response.data || []);
        } catch (error) {
            console.error('Failed to fetch parameters:', error);
            setAvailableParameters([]);
        }
    };

    const fetchRegulationsForSampleType = async (sampleTypeId: number) => {
        setIsLoadingRegulations(true);
        try {
            const response = await axios.get(`/operation/lims-master/sample-types/${sampleTypeId}/regulations`);
            setFilteredRegulations(response.data.data || []);

            // Get selected regulation IDs for this sample type
            const selectedIds = response.data.data
                .filter((r: Regulation) => r.sample_type_ids?.includes(sampleTypeId))
                .map((r: Regulation) => r.id);
            setSelectedRegulationIds(selectedIds);
        } catch (error) {
            toast.error('Gagal mengambil data regulasi');
            setFilteredRegulations([]);
        } finally {
            setIsLoadingRegulations(false);
        }
    };

    const fetchAttachmentsForRegulation = async (regulationId: number) => {
        setIsLoadingAttachments(true);
        try {
            const response = await axios.get(`/operation/lims-master/regulations/${regulationId}/attachments`);
            setFilteredAttachments(response.data.data || []);
        } catch (error) {
            toast.error('Gagal mengambil data lampiran');
            setFilteredAttachments([]);
        } finally {
            setIsLoadingAttachments(false);
        }
    };

    const fetchParametersForAttachment = async (attachmentId: number) => {
        setIsLoadingParameters(true);
        try {
            const response = await axios.get(`/operation/lims-master/attachments/${attachmentId}/parameters`);
            setFilteredParameters(response.data.data || []);
        } catch (error) {
            toast.error('Gagal mengambil data parameter');
            setFilteredParameters([]);
        } finally {
            setIsLoadingParameters(false);
        }
    };

    // Sample Type handlers
    const handleSelectSampleType = (st: SampleType) => {
        setSelectedSampleType(st);
    };

    const handleAddSampleType = () => {
        setSelectedSampleTypeForEdit(null);
        setIsSampleTypeDrawerOpen(true);
    };

    const handleEditSampleType = (st: SampleType) => {
        setSelectedSampleTypeForEdit(st);
        setIsSampleTypeDrawerOpen(true);
    };

    const handleDeleteSampleType = (st: SampleType) => {
        setSelectedSampleTypeForEdit(st);
        setDeleteTarget('sample-type');
        setIsDeleteDialogOpen(true);
    };

    const handleSampleTypeSubmit = (data: any) => {
        setIsSubmitting(true);

        const url = selectedSampleTypeForEdit
            ? `/operation/sample-type/${selectedSampleTypeForEdit.id}`
            : '/operation/sample-type';

        const method = selectedSampleTypeForEdit ? 'put' : 'post';

        router[method](url, data, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success(
                    selectedSampleTypeForEdit
                        ? 'Jenis sampel berhasil diperbarui'
                        : 'Jenis sampel berhasil ditambahkan'
                );
                setIsSampleTypeDrawerOpen(false);
                setSelectedSampleTypeForEdit(null);
            },
            onError: (errors) => {
                const errorMessage = Object.values(errors).flat().join(', ');
                toast.error(errorMessage || 'Terjadi kesalahan');
            },
            onFinish: () => {
                setIsSubmitting(false);
            },
        });
    };

    // Regulation handlers
    const handleSelectRegulation = (r: Regulation) => {
        setSelectedRegulation(r);
    };

    const handleManageRelation = () => {
        if (!selectedSampleType) {
            toast.error('Pilih jenis sampel terlebih dahulu');
            return;
        }
        setIsRelationDrawerOpen(true);
    };

    const handleAddRegulation = () => {
        setSelectedRegulationForEdit(null);
        setIsRegulationDrawerOpen(true);
    };

    const handleEditRegulation = (r: Regulation) => {
        setSelectedRegulationForEdit(r);
        setIsRegulationDrawerOpen(true);
    };

    const handleDeleteRegulation = (r: Regulation) => {
        setSelectedRegulationForEdit(r);
        setDeleteTarget('regulation');
        setIsDeleteDialogOpen(true);
    };

    const handleRegulationSubmit = (data: any) => {
        setIsSubmitting(true);

        const url = selectedRegulationForEdit
            ? `/operation/regulation/${selectedRegulationForEdit.id}`
            : '/operation/regulation';

        // Use post for both since we handle multipart/form-data for file uploads
        // For updates, Laravel needs _method=PUT
        const formData = new FormData();
        Object.keys(data).forEach(key => {
            if (data[key] !== null && data[key] !== undefined) {
                if (key === 'effective_date' || key === 'expiry_date') {
                    formData.append(key, data[key].toISOString().split('T')[0]);
                } else if (key === 'sample_type_ids' && Array.isArray(data[key])) {
                    data[key].forEach((id: number) => {
                        formData.append('sample_type_ids[]', id.toString());
                    });
                } else {
                    formData.append(key, data[key]);
                }
            }
        });

        if (selectedRegulationForEdit) {
            formData.append('_method', 'PUT');
        }

        router.post(url, formData as any, {
            preserveScroll: true,
            forceFormData: true,
            onSuccess: () => {
                toast.success(
                    selectedRegulationForEdit
                        ? 'Regulasi berhasil diperbarui'
                        : 'Regulasi berhasil ditambahkan'
                );
                setIsRegulationDrawerOpen(false);
                setSelectedRegulationForEdit(null);

                // Refresh regulations list if needed
                if (selectedSampleType) {
                    fetchRegulationsForSampleType(selectedSampleType.id);
                }
            },
            onError: (errors) => {
                const errorMessage = Object.values(errors).flat().join(', ');
                toast.error(errorMessage || 'Terjadi kesalahan');
            },
            onFinish: () => {
                setIsSubmitting(false);
            },
        });
    };

    const handleSaveRelation = async (regulationIds: number[]) => {
        if (!selectedSampleType) return;

        setIsSubmitting(true);
        try {
            await axios.post(`/operation/lims-master/sample-types/${selectedSampleType.id}/sync-regulations`, {
                regulation_ids: regulationIds,
            });
            toast.success('Relasi regulasi berhasil disimpan');
            setIsRelationDrawerOpen(false);
            setSelectedRegulationIds(regulationIds);

            // Refresh regulations list
            fetchRegulationsForSampleType(selectedSampleType.id);
        } catch (error: any) {
            toast.error(error.response?.data?.message || 'Gagal menyimpan relasi');
        } finally {
            setIsSubmitting(false);
        }
    };

    // Attachment handlers
    const handleSelectAttachment = (a: RegulationAttachment) => {
        setSelectedAttachment(a);
    };

    const handleAddAttachment = () => {
        if (!selectedRegulation) {
            toast.error('Pilih regulasi terlebih dahulu');
            return;
        }
        setSelectedAttachmentForEdit(null);
        setIsAttachmentDrawerOpen(true);
    };

    const handleEditAttachment = (a: RegulationAttachment) => {
        setSelectedAttachmentForEdit(a);
        setIsAttachmentDrawerOpen(true);
    };

    const handleDeleteAttachment = (a: RegulationAttachment) => {
        setSelectedAttachmentForEdit(a);
        setDeleteTarget('attachment');
        setIsDeleteDialogOpen(true);
    };

    const handleAttachmentSubmit = (formData: FormData) => {
        setIsSubmitting(true);

        const url = selectedAttachmentForEdit
            ? `/operation/regulation-attachment/${selectedAttachmentForEdit.id}`
            : '/operation/regulation-attachment';

        const method = selectedAttachmentForEdit ? 'post' : 'post';

        // Add _method for Laravel
        if (selectedAttachmentForEdit) {
            formData.append('_method', 'PUT');
        }

        router.post(url, formData as any, {
            preserveScroll: true,
            forceFormData: true,
            onSuccess: () => {
                toast.success(
                    selectedAttachmentForEdit
                        ? 'Lampiran berhasil diperbarui'
                        : 'Lampiran berhasil ditambahkan'
                );
                setIsAttachmentDrawerOpen(false);
                setSelectedAttachmentForEdit(null);

                // Refresh attachments list
                if (selectedRegulation) {
                    fetchAttachmentsForRegulation(selectedRegulation.id);
                }
            },
            onError: (errors) => {
                const errorMessage = Object.values(errors).flat().join(', ');
                toast.error(errorMessage || 'Terjadi kesalahan');
            },
            onFinish: () => {
                setIsSubmitting(false);
            },
        });
    };

    // Parameter handlers
    const handleAddParameter = () => {
        if (!selectedAttachment) {
            toast.error('Pilih lampiran terlebih dahulu');
            return;
        }
        setSelectedParameter(null);
        setIsParameterDrawerOpen(true);
    };

    const handleEditParameter = (p: AttachmentParameterStandard) => {
        setSelectedParameter(p);
        setIsParameterDrawerOpen(true);
    };

    const handleDeleteParameter = (p: AttachmentParameterStandard) => {
        setSelectedParameter(p);
        setDeleteTarget('parameter');
        setIsDeleteDialogOpen(true);
    };

    const handleParameterSubmit = (data: any) => {
        setIsSubmitting(true);

        const url = selectedParameter
            ? `/operation/attachment-parameter-standard/${selectedParameter.id}`
            : '/operation/attachment-parameter-standard';

        const method = selectedParameter ? 'put' : 'post';

        router[method](url, data, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success(
                    selectedParameter
                        ? 'Parameter berhasil diperbarui'
                        : 'Parameter berhasil ditambahkan'
                );
                setIsParameterDrawerOpen(false);
                setSelectedParameter(null);

                // Refresh parameter list
                if (selectedAttachment) {
                    fetchParametersForAttachment(selectedAttachment.id);
                }
            },
            onError: (errors) => {
                const errorMessage = Object.values(errors).flat().join(', ');
                toast.error(errorMessage || 'Terjadi kesalahan');
            },
            onFinish: () => {
                setIsSubmitting(false);
            },
        });
    };

    const confirmDelete = () => {
        if (deleteTarget === 'sample-type' && selectedSampleTypeForEdit) {
            deleteSampleType();
        } else if (deleteTarget === 'regulation' && selectedRegulationForEdit) {
            deleteRegulation();
        } else if (deleteTarget === 'attachment' && selectedAttachmentForEdit) {
            deleteAttachment();
        } else if (deleteTarget === 'parameter' && selectedParameter) {
            deleteParameter();
        }
    };

    const deleteSampleType = () => {
        if (!selectedSampleTypeForEdit) return;

        setIsDeleting(true);

        router.delete(`/operation/sample-type/${selectedSampleTypeForEdit.id}`, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success('Jenis sampel berhasil dihapus');
                setIsDeleteDialogOpen(false);
                setSelectedSampleTypeForEdit(null);
                if (selectedSampleType?.id === selectedSampleTypeForEdit.id) {
                    setSelectedSampleType(null);
                }
            },
            onError: (errors) => {
                const errorMessage = Object.values(errors).flat().join(', ');
                toast.error(errorMessage || 'Gagal menghapus jenis sampel');
            },
            onFinish: () => {
                setIsDeleting(false);
            },
        });
    };

    const deleteRegulation = () => {
        if (!selectedRegulationForEdit) return;

        setIsDeleting(true);

        router.delete(`/operation/regulation/${selectedRegulationForEdit.id}`, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success('Regulasi berhasil dihapus');
                setIsDeleteDialogOpen(false);
                setSelectedRegulationForEdit(null);

                // Refresh regulations list
                if (selectedSampleType) {
                    fetchRegulationsForSampleType(selectedSampleType.id);
                }
            },
            onError: (errors) => {
                const errorMessage = Object.values(errors).flat().join(', ');
                toast.error(errorMessage || 'Gagal menghapus regulasi');
            },
            onFinish: () => {
                setIsDeleting(false);
            },
        });
    };

    const deleteAttachment = () => {
        if (!selectedAttachmentForEdit) return;

        setIsDeleting(true);

        router.delete(`/operation/regulation-attachment/${selectedAttachmentForEdit.id}`, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success('Lampiran berhasil dihapus');
                setIsDeleteDialogOpen(false);
                setSelectedAttachmentForEdit(null);

                // Refresh attachments list
                if (selectedRegulation) {
                    fetchAttachmentsForRegulation(selectedRegulation.id);
                }
            },
            onError: (errors) => {
                const errorMessage = Object.values(errors).flat().join(', ');
                toast.error(errorMessage || 'Gagal menghapus lampiran');
            },
            onFinish: () => {
                setIsDeleting(false);
            },
        });
    };

    const deleteParameter = () => {
        if (!selectedParameter) return;

        setIsDeleting(true);

        router.delete(`/operation/attachment-parameter-standard/${selectedParameter.id}`, {
            preserveScroll: true,
            onSuccess: () => {
                toast.success('Parameter berhasil dihapus');
                setIsDeleteDialogOpen(false);
                setSelectedParameter(null);

                // Refresh parameter list
                if (selectedAttachment) {
                    fetchParametersForAttachment(selectedAttachment.id);
                }
            },
            onError: (errors) => {
                const errorMessage = Object.values(errors).flat().join(', ');
                toast.error(errorMessage || 'Gagal menghapus parameter');
            },
            onFinish: () => {
                setIsDeleting(false);
            },
        });
    };

    return (
        <AppLayout>
            <Head title="Master Data LIMS" />

            <div className="flex flex-col h-[calc(100vh-4rem)]">
                {/* Header */}
                <div className="p-4 border-b bg-background">
                    <div className="flex items-center gap-3">
                        <FlaskConical className="h-6 w-6 text-primary" />
                        <div>
                            <h1 className="text-xl font-bold">Master Data LIMS</h1>
                            <p className="text-sm text-muted-foreground">
                                Kelola Jenis Sampel, Regulasi, Lampiran, dan Parameter Uji dengan Baku Mutu
                            </p>
                        </div>
                    </div>
                </div>

                {/* 4-Column Layout */}
                <div className="flex-1 flex overflow-hidden">
                    {/* Column 1: Sample Types */}
                    <div className="w-1/4 min-w-[250px]">
                        <SampleTypeList
                            sampleTypes={sampleTypes.data}
                            selectedId={selectedSampleType?.id || null}
                            onSelect={handleSelectSampleType}
                            onAdd={handleAddSampleType}
                            onEdit={handleEditSampleType}
                            onDelete={handleDeleteSampleType}
                        />
                    </div>

                    {/* Column 2: Regulations */}
                    <div className="w-1/4 min-w-[250px]">
                        <RegulationList
                            regulations={filteredRegulations}
                            selectedId={selectedRegulation?.id || null}
                            onSelect={handleSelectRegulation}
                            onAdd={handleAddRegulation}
                            onEdit={handleEditRegulation}
                            onDelete={handleDeleteRegulation}
                            onManageRelation={handleManageRelation}
                            sampleTypeName={selectedSampleType?.name}
                        />
                    </div>

                    {/* Column 3: Attachments */}
                    <div className="w-1/4 min-w-[250px]">
                        <AttachmentList
                            attachments={filteredAttachments}
                            selectedId={selectedAttachment?.id || null}
                            onSelect={handleSelectAttachment}
                            onAdd={handleAddAttachment}
                            onEdit={handleEditAttachment}
                            onDelete={handleDeleteAttachment}
                            regulationName={selectedRegulation?.name}
                        />
                    </div>

                    {/* Column 4: Parameters */}
                    <div className="flex-1">
                        <ParameterList
                            parameters={filteredParameters}
                            onAdd={handleAddParameter}
                            onEdit={handleEditParameter}
                            onDelete={handleDeleteParameter}
                            sampleTypeName={selectedSampleType?.name}
                            regulationName={selectedRegulation?.name}
                            attachmentName={selectedAttachment?.name || selectedAttachment?.file_name}
                            isLoading={isLoadingParameters}
                        />
                    </div>
                </div>
            </div>

            {/* Sample Type Form Drawer */}
            <ResizableDrawer
                open={isSampleTypeDrawerOpen}
                onOpenChange={setIsSampleTypeDrawerOpen}
                title={selectedSampleTypeForEdit ? 'Edit Jenis Sampel' : 'Tambah Jenis Sampel'}
                description={
                    selectedSampleTypeForEdit
                        ? 'Perbarui data jenis sampel'
                        : 'Tambahkan jenis sampel baru'
                }
            >
                <div className="p-4">
                    <SampleTypeForm
                        sampleType={selectedSampleTypeForEdit || undefined}
                        categories={sampleTypeCategories.data}
                        lhuFormats={lhuFormats.data}
                        methods={methods.data}
                        onSubmit={handleSampleTypeSubmit}
                        isSubmitting={isSubmitting}
                    />
                </div>
            </ResizableDrawer>

            {/* Regulation Form Drawer */}
            <ResizableDrawer
                open={isRegulationDrawerOpen}
                onOpenChange={setIsRegulationDrawerOpen}
                title={selectedRegulationForEdit ? 'Edit Regulasi' : 'Tambah Regulasi'}
                description={
                    selectedRegulationForEdit
                        ? 'Perbarui data regulasi'
                        : 'Tambahkan regulasi baru'
                }
            >
                <div className="p-4">
                    <RegulationForm
                        regulation={selectedRegulationForEdit || undefined}
                        sampleTypes={sampleTypes.data}
                        onSubmit={handleRegulationSubmit}
                        isSubmitting={isSubmitting}
                    />
                </div>
            </ResizableDrawer>

            {/* Relation Management Drawer */}
            <ResizableDrawer
                open={isRelationDrawerOpen}
                onOpenChange={setIsRelationDrawerOpen}
                title="Kelola Relasi Regulasi"
                description={`Pilih regulasi yang berlaku untuk ${selectedSampleType?.name}`}
            >
                {selectedSampleType && (
                    <RegulationRelationManager
                        sampleTypeId={selectedSampleType.id}
                        sampleTypeName={selectedSampleType.name}
                        availableRegulations={regulations.data}
                        selectedRegulationIds={selectedRegulationIds}
                        onSave={handleSaveRelation}
                        onCancel={() => setIsRelationDrawerOpen(false)}
                        isSaving={isSubmitting}
                    />
                )}
            </ResizableDrawer>

            {/* Attachment Form Drawer */}
            <ResizableDrawer
                open={isAttachmentDrawerOpen}
                onOpenChange={setIsAttachmentDrawerOpen}
                title={selectedAttachmentForEdit ? 'Edit Lampiran' : 'Tambah Lampiran'}
                description={
                    selectedAttachmentForEdit
                        ? `Perbarui lampiran untuk ${selectedRegulation?.name}`
                        : `Tambahkan lampiran baru untuk ${selectedRegulation?.name}`
                }
            >
                {selectedRegulation && (
                    <AttachmentForm
                        regulationId={selectedRegulation.id}
                        attachment={selectedAttachmentForEdit}
                        onSubmit={handleAttachmentSubmit}
                        onCancel={() => setIsAttachmentDrawerOpen(false)}
                        isSubmitting={isSubmitting}
                    />
                )}
            </ResizableDrawer>

            {/* Parameter Form Drawer */}
            <ResizableDrawer
                open={isParameterDrawerOpen}
                onOpenChange={setIsParameterDrawerOpen}
                title={selectedParameter ? 'Edit Parameter & Baku Mutu' : 'Tambah Parameter & Baku Mutu'}
                description={
                    selectedParameter
                        ? `Perbarui parameter dan baku mutu untuk ${selectedAttachment?.name || selectedAttachment?.file_name}`
                        : `Tambahkan parameter baru dengan baku mutu untuk ${selectedAttachment?.name || selectedAttachment?.file_name}`
                }
            >
                {selectedAttachment && (
                    <ParameterBakuMutuForm
                        attachmentId={selectedAttachment.id}
                        parameterStandard={selectedParameter}
                        availableParameters={availableParameters}
                        units={units.data}
                        onSubmit={handleParameterSubmit}
                        onCancel={() => setIsParameterDrawerOpen(false)}
                        isSubmitting={isSubmitting}
                    />
                )}
            </ResizableDrawer>

            {/* Delete Confirmation Dialog */}
            <DeleteConfirmationDialog
                open={isDeleteDialogOpen}
                onOpenChange={setIsDeleteDialogOpen}
                onConfirm={confirmDelete}
                title={
                    deleteTarget === 'sample-type' ? 'Hapus Jenis Sampel' :
                        deleteTarget === 'regulation' ? 'Hapus Regulasi' :
                            deleteTarget === 'attachment' ? 'Hapus Lampiran' :
                                'Hapus Parameter'
                }
                description={
                    deleteTarget === 'sample-type'
                        ? `Apakah Anda yakin ingin menghapus jenis sampel "${selectedSampleTypeForEdit?.name}"?` :
                        deleteTarget === 'regulation'
                            ? `Apakah Anda yakin ingin menghapus regulasi "${selectedRegulationForEdit?.name}"? Tindakan ini tidak dapat dibatalkan.` :
                            deleteTarget === 'attachment'
                                ? `Apakah Anda yakin ingin menghapus lampiran "${selectedAttachmentForEdit?.name || selectedAttachmentForEdit?.file_name}"? Tindakan ini tidak dapat dibatalkan.` :
                                `Apakah Anda yakin ingin menghapus parameter "${selectedParameter?.parameter_name || selectedParameter?.display_name}"? Tindakan ini tidak dapat dibatalkan.`
                }
                isDeleting={isDeleting}
            />
        </AppLayout>
    );
}
