import branchesRoutes from '@/actions/App/Http/Controllers/BranchController';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { DataTable } from '@/components/ui/data-table';
import {
    Dialog,
    DialogContent,
    DialogDescription,
    DialogFooter,
    DialogHeader,
    DialogTitle,
} from '@/components/ui/dialog';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
    InputGroup,
    InputGroupAddon,
    InputGroupInput,
} from '@/components/ui/input-group';
import { Label } from '@/components/ui/label';
import { StatusBadge } from '@/components/ui/status-badge';
import { usePermissions } from '@/hooks/use-permissions';
import AppLayout from '@/layouts/app-layout';
import { useFilterParams } from '@/lib/hooks/useFilterParams';
import { toastError, toastLoading, toastSuccess } from '@/lib/toast';
import type {
    Branch,
    BranchFilters,
    BreadcrumbItem,
    PaginatedData,
} from '@/types';
import { Head, Link, router, useForm } from '@inertiajs/react';
import type { ColumnDef } from '@tanstack/react-table';
import {
    Building2,
    Edit2,
    MoreHorizontal,
    Plus,
    Search,
    SearchIcon,
    Trash2,
} from 'lucide-react';
import { useState } from 'react';

interface PageProps {
    branches: PaginatedData<Branch>;
    filters: BranchFilters;
}

const breadcrumbs: BreadcrumbItem[] = [
    {
        title: 'Cabang',
        href: branchesRoutes.index().url,
    },
];

export default function Index({ branches, filters }: PageProps) {
    const { can } = usePermissions();
    const [showCreateModal, setShowCreateModal] = useState(false);
    const [showEditModal, setShowEditModal] = useState(false);
    const [showDeleteModal, setShowDeleteModal] = useState(false);
    const [selectedBranch, setSelectedBranch] = useState<Branch | null>(null);

    // Use filter params hook
    const { updatePage, search } = useFilterParams({
        baseUrl: branchesRoutes.index().url,
    });

    const goToNextPage = () => updatePage(branches.current_page + 1);
    const goToPrevPage = () => updatePage(branches.current_page - 1);

    // Create form
    const createForm = useForm({
        code: '',
        name: '',
        address: '',
        city: '',
        province: '',
        phone: '',
        email: '',
        is_headquarters: false,
        is_active: true,
    });

    const handleSubmitCreate = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        createForm.post(branchesRoutes.store().url, {
            onStart: () => toastLoading('Menyimpan cabang...'),
            onSuccess: () => {
                toastSuccess('Cabang berhasil ditambahkan');
                setShowCreateModal(false);
                createForm.reset();
            },
            onError: () => toastError('Gagal menyimpan cabang'),
        });
    };

    // Edit form
    const editForm = useForm({
        code: '',
        name: '',
        address: '',
        city: '',
        province: '',
        phone: '',
        email: '',
        is_headquarters: false,
        is_active: true,
    });

    const handleEditBranch = (branch: Branch) => {
        setSelectedBranch(branch);
        editForm.setData({
            code: branch.code,
            name: branch.name,
            address: branch.address || '',
            city: branch.city || '',
            province: branch.province || '',
            phone: branch.phone || '',
            email: branch.email || '',
            is_headquarters: branch.is_headquarters,
            is_active: branch.is_active,
        });
        setShowEditModal(true);
    };

    const handleSubmitEdit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        if (!selectedBranch) return;

        editForm.put(branchesRoutes.update({ branch: selectedBranch.id }).url, {
            onStart: () => toastLoading('Memperbarui cabang...'),
            onSuccess: () => {
                toastSuccess('Cabang berhasil diperbarui');
                setShowEditModal(false);
                setSelectedBranch(null);
                editForm.reset();
            },
            onError: () => toastError('Gagal memperbarui cabang'),
        });
    };

    // Delete
    const handleDeleteBranch = (branch: Branch) => {
        setSelectedBranch(branch);
        setShowDeleteModal(true);
    };

    const handleConfirmDelete = () => {
        if (!selectedBranch) return;

        router.delete(
            branchesRoutes.destroy({ branch: selectedBranch.id }).url,
            {
                onStart: () => toastLoading('Menghapus cabang...'),
                onSuccess: () => {
                    toastSuccess('Cabang berhasil dihapus');
                    setShowDeleteModal(false);
                    setSelectedBranch(null);
                },
                onError: () => toastError('Gagal menghapus cabang'),
            },
        );
    };

    const columns: ColumnDef<Branch>[] = [
        {
            accessorKey: 'code',
            header: 'Kode',
            cell: ({ row }) => (
                <span className="font-mono">{row.getValue('code')}</span>
            ),
        },
        { accessorKey: 'name', header: 'Nama Cabang' },
        { accessorKey: 'city', header: 'Kota' },
        {
            accessorKey: 'phone',
            header: 'Telepon',
            cell: ({ row }) => row.getValue('phone') || '-',
        },
        {
            accessorKey: 'is_headquarters',
            header: 'Pusat',
            cell: ({ row }) =>
                row.getValue('is_headquarters') ? (
                    <span className="inline-flex items-center">
                        <Building2 className="mr-1 h-3 w-3" />
                        Ya
                    </span>
                ) : (
                    '-'
                ),
        },
        {
            accessorKey: 'is_active',
            header: 'Status',
            cell: ({ row }) => (
                <StatusBadge
                    type="branch"
                    status={row.getValue('is_active') ? 'active' : 'inactive'}
                />
            ),
        },
        {
            id: 'actions',
            cell: ({ row }) => {
                const branch = row.original;

                return (
                    <DropdownMenu>
                        <DropdownMenuTrigger asChild>
                            <Button variant="ghost" className="h-8 w-8 p-0">
                                <span className="sr-only">Buka menu</span>
                                <MoreHorizontal className="h-4 w-4" />
                            </Button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="end">
                            <DropdownMenuItem asChild>
                                <Link
                                    href={
                                        branchesRoutes.show({
                                            branch: branch.id,
                                        }).url
                                    }
                                >
                                    <Search className="mr-2 h-4 w-4" />
                                    Show
                                </Link>
                            </DropdownMenuItem>
                            {can('branches.update') && (
                                <DropdownMenuItem
                                    onClick={() => handleEditBranch(branch)}
                                >
                                    <Edit2 className="mr-2 h-4 w-4" />
                                    Edit
                                </DropdownMenuItem>
                            )}
                            {can('branches.delete') && (
                                <DropdownMenuItem
                                    className="text-destructive"
                                    onClick={() => handleDeleteBranch(branch)}
                                >
                                    <Trash2 className="mr-2 h-4 w-4" />
                                    Hapus
                                </DropdownMenuItem>
                            )}
                        </DropdownMenuContent>
                    </DropdownMenu>
                );
            },
        },
    ];

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title="Cabang" />

            <div className="flex h-full flex-1 flex-col gap-4 overflow-x-auto rounded-xl p-4">
                {/* Header */}
                <div className="flex items-center justify-between">
                    <div className="flex flex-col gap-1">
                        <h1 className="text-2xl font-black">
                            Manajemen Cabang
                        </h1>
                        <span className="text-sm text-muted-foreground">
                            Kelola cabang koperasi dan informasinya.
                        </span>
                    </div>
                    {can('branches.create') && (
                        <Button onClick={() => setShowCreateModal(true)}>
                            <Plus className="mr-2 h-4 w-4" />
                            Tambah Cabang
                        </Button>
                    )}
                </div>

                {/* Search */}
                <div className="flex flex-col gap-4 md:flex-row md:gap-4">
                    <div className="flex w-full md:w-1/2">
                        <InputGroup className="max-w-md flex-1">
                            <InputGroupInput
                                id="search"
                                placeholder="Cari berdasarkan nama atau kode..."
                                defaultValue={filters.search}
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter') {
                                        search(e.currentTarget.value);
                                    }
                                }}
                                onBlur={(e) => search(e.currentTarget.value)}
                            />
                            <InputGroupAddon align="inline-start">
                                <SearchIcon className="h-4 w-4" />
                            </InputGroupAddon>
                        </InputGroup>
                    </div>
                </div>

                {/* Table */}
                <DataTable
                    columns={columns}
                    data={branches.data}
                    pagination={{
                        currentPage: branches.current_page,
                        lastPage: branches.last_page,
                        onNext: goToNextPage,
                        onPrev: goToPrevPage,
                    }}
                />
            </div>

            {/* Create Modal */}
            <Dialog open={showCreateModal} onOpenChange={setShowCreateModal}>
                <DialogContent className="max-w-2xl">
                    <DialogHeader>
                        <DialogTitle>Tambah Cabang Baru</DialogTitle>
                        <DialogDescription>
                            Isi data cabang yang akan ditambahkan.
                        </DialogDescription>
                    </DialogHeader>
                    <form onSubmit={handleSubmitCreate}>
                        <div className="grid gap-4 py-4">
                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="code">Kode Cabang *</Label>
                                    <input
                                        id="code"
                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                                        value={createForm.data.code}
                                        onChange={(e) =>
                                            createForm.setData(
                                                'code',
                                                e.target.value,
                                            )
                                        }
                                        placeholder="Contoh: CAB01"
                                    />
                                    {createForm.errors.code && (
                                        <p className="text-sm text-destructive">
                                            {createForm.errors.code}
                                        </p>
                                    )}
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="name">Nama Cabang *</Label>
                                    <input
                                        id="name"
                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                                        value={createForm.data.name}
                                        onChange={(e) =>
                                            createForm.setData(
                                                'name',
                                                e.target.value,
                                            )
                                        }
                                        placeholder="Nama lengkap cabang"
                                    />
                                    {createForm.errors.name && (
                                        <p className="text-sm text-destructive">
                                            {createForm.errors.name}
                                        </p>
                                    )}
                                </div>
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="address">Alamat</Label>
                                <input
                                    id="address"
                                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                                    value={createForm.data.address}
                                    onChange={(e) =>
                                        createForm.setData(
                                            'address',
                                            e.target.value,
                                        )
                                    }
                                    placeholder="Alamat lengkap"
                                />
                                {createForm.errors.address && (
                                    <p className="text-sm text-destructive">
                                        {createForm.errors.address}
                                    </p>
                                )}
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="city">Kota</Label>
                                    <input
                                        id="city"
                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                                        value={createForm.data.city}
                                        onChange={(e) =>
                                            createForm.setData(
                                                'city',
                                                e.target.value,
                                            )
                                        }
                                        placeholder="Kota"
                                    />
                                    {createForm.errors.city && (
                                        <p className="text-sm text-destructive">
                                            {createForm.errors.city}
                                        </p>
                                    )}
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="province">Provinsi</Label>
                                    <input
                                        id="province"
                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                                        value={createForm.data.province}
                                        onChange={(e) =>
                                            createForm.setData(
                                                'province',
                                                e.target.value,
                                            )
                                        }
                                        placeholder="Provinsi"
                                    />
                                    {createForm.errors.province && (
                                        <p className="text-sm text-destructive">
                                            {createForm.errors.province}
                                        </p>
                                    )}
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="phone">Telepon</Label>
                                    <input
                                        id="phone"
                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                                        value={createForm.data.phone}
                                        onChange={(e) =>
                                            createForm.setData(
                                                'phone',
                                                e.target.value,
                                            )
                                        }
                                        placeholder="Contoh: 02112345678"
                                    />
                                    {createForm.errors.phone && (
                                        <p className="text-sm text-destructive">
                                            {createForm.errors.phone}
                                        </p>
                                    )}
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="email">Email</Label>
                                    <input
                                        id="email"
                                        type="email"
                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                                        value={createForm.data.email}
                                        onChange={(e) =>
                                            createForm.setData(
                                                'email',
                                                e.target.value,
                                            )
                                        }
                                        placeholder="email@cabang.com"
                                    />
                                    {createForm.errors.email && (
                                        <p className="text-sm text-destructive">
                                            {createForm.errors.email}
                                        </p>
                                    )}
                                </div>
                            </div>

                            <div className="flex gap-6 pt-2">
                                <div className="flex items-center space-x-2">
                                    <Checkbox
                                        id="is_headquarters"
                                        checked={
                                            createForm.data.is_headquarters
                                        }
                                        onCheckedChange={(checked) =>
                                            createForm.setData(
                                                'is_headquarters',
                                                checked,
                                            )
                                        }
                                    />
                                    <Label
                                        htmlFor="is_headquarters"
                                        className="cursor-pointer"
                                    >
                                        Cabang Pusat
                                    </Label>
                                </div>
                                <div className="flex items-center space-x-2">
                                    <Checkbox
                                        id="is_active"
                                        checked={createForm.data.is_active}
                                        onCheckedChange={(checked) =>
                                            createForm.setData(
                                                'is_active',
                                                checked,
                                            )
                                        }
                                    />
                                    <Label
                                        htmlFor="is_active"
                                        className="cursor-pointer"
                                    >
                                        Aktif
                                    </Label>
                                </div>
                            </div>
                        </div>
                        <DialogFooter>
                            <Button
                                type="button"
                                variant="outline"
                                onClick={() => {
                                    setShowCreateModal(false);
                                    createForm.reset();
                                }}
                                disabled={createForm.processing}
                            >
                                Batal
                            </Button>
                            <Button
                                type="submit"
                                disabled={createForm.processing}
                            >
                                {createForm.processing
                                    ? 'Menyimpan...'
                                    : 'Simpan'}
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            {/* Edit Modal */}
            <Dialog open={showEditModal} onOpenChange={setShowEditModal}>
                <DialogContent className="max-w-2xl">
                    <DialogHeader>
                        <DialogTitle>Edit Cabang</DialogTitle>
                        <DialogDescription>
                            Perbarui data cabang.
                        </DialogDescription>
                    </DialogHeader>
                    <form onSubmit={handleSubmitEdit}>
                        <div className="grid gap-4 py-4">
                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="edit_code">
                                        Kode Cabang *
                                    </Label>
                                    <input
                                        id="edit_code"
                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                                        value={editForm.data.code}
                                        onChange={(e) =>
                                            editForm.setData(
                                                'code',
                                                e.target.value,
                                            )
                                        }
                                        placeholder="Contoh: CAB01"
                                    />
                                    {editForm.errors.code && (
                                        <p className="text-sm text-destructive">
                                            {editForm.errors.code}
                                        </p>
                                    )}
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="edit_name">
                                        Nama Cabang *
                                    </Label>
                                    <input
                                        id="edit_name"
                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                                        value={editForm.data.name}
                                        onChange={(e) =>
                                            editForm.setData(
                                                'name',
                                                e.target.value,
                                            )
                                        }
                                        placeholder="Nama lengkap cabang"
                                    />
                                    {editForm.errors.name && (
                                        <p className="text-sm text-destructive">
                                            {editForm.errors.name}
                                        </p>
                                    )}
                                </div>
                            </div>

                            <div className="space-y-2">
                                <Label htmlFor="edit_address">Alamat</Label>
                                <input
                                    id="edit_address"
                                    className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                                    value={editForm.data.address}
                                    onChange={(e) =>
                                        editForm.setData(
                                            'address',
                                            e.target.value,
                                        )
                                    }
                                    placeholder="Alamat lengkap"
                                />
                                {editForm.errors.address && (
                                    <p className="text-sm text-destructive">
                                        {editForm.errors.address}
                                    </p>
                                )}
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="edit_city">Kota</Label>
                                    <input
                                        id="edit_city"
                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                                        value={editForm.data.city}
                                        onChange={(e) =>
                                            editForm.setData(
                                                'city',
                                                e.target.value,
                                            )
                                        }
                                        placeholder="Kota"
                                    />
                                    {editForm.errors.city && (
                                        <p className="text-sm text-destructive">
                                            {editForm.errors.city}
                                        </p>
                                    )}
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="edit_province">
                                        Provinsi
                                    </Label>
                                    <input
                                        id="edit_province"
                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                                        value={editForm.data.province}
                                        onChange={(e) =>
                                            editForm.setData(
                                                'province',
                                                e.target.value,
                                            )
                                        }
                                        placeholder="Provinsi"
                                    />
                                    {editForm.errors.province && (
                                        <p className="text-sm text-destructive">
                                            {editForm.errors.province}
                                        </p>
                                    )}
                                </div>
                            </div>

                            <div className="grid grid-cols-2 gap-4">
                                <div className="space-y-2">
                                    <Label htmlFor="edit_phone">Telepon</Label>
                                    <input
                                        id="edit_phone"
                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                                        value={editForm.data.phone}
                                        onChange={(e) =>
                                            editForm.setData(
                                                'phone',
                                                e.target.value,
                                            )
                                        }
                                        placeholder="Contoh: 02112345678"
                                    />
                                    {editForm.errors.phone && (
                                        <p className="text-sm text-destructive">
                                            {editForm.errors.phone}
                                        </p>
                                    )}
                                </div>
                                <div className="space-y-2">
                                    <Label htmlFor="edit_email">Email</Label>
                                    <input
                                        id="edit_email"
                                        type="email"
                                        className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
                                        value={editForm.data.email}
                                        onChange={(e) =>
                                            editForm.setData(
                                                'email',
                                                e.target.value,
                                            )
                                        }
                                        placeholder="email@cabang.com"
                                    />
                                    {editForm.errors.email && (
                                        <p className="text-sm text-destructive">
                                            {editForm.errors.email}
                                        </p>
                                    )}
                                </div>
                            </div>

                            <div className="flex gap-6 pt-2">
                                <div className="flex items-center space-x-2">
                                    <Checkbox
                                        id="edit_is_headquarters"
                                        checked={editForm.data.is_headquarters}
                                        onCheckedChange={(checked) =>
                                            editForm.setData(
                                                'is_headquarters',
                                                checked,
                                            )
                                        }
                                    />
                                    <Label
                                        htmlFor="edit_is_headquarters"
                                        className="cursor-pointer"
                                    >
                                        Cabang Pusat
                                    </Label>
                                </div>
                                <div className="flex items-center space-x-2">
                                    <Checkbox
                                        id="edit_is_active"
                                        checked={editForm.data.is_active}
                                        onCheckedChange={(checked) =>
                                            editForm.setData(
                                                'is_active',
                                                checked,
                                            )
                                        }
                                    />
                                    <Label
                                        htmlFor="edit_is_active"
                                        className="cursor-pointer"
                                    >
                                        Aktif
                                    </Label>
                                </div>
                            </div>
                        </div>
                        <DialogFooter>
                            <Button
                                type="button"
                                variant="outline"
                                onClick={() => {
                                    setShowEditModal(false);
                                    setSelectedBranch(null);
                                    editForm.reset();
                                }}
                            >
                                Batal
                            </Button>
                            <Button
                                type="submit"
                                disabled={editForm.processing}
                            >
                                {editForm.processing
                                    ? 'Menyimpan...'
                                    : 'Simpan'}
                            </Button>
                        </DialogFooter>
                    </form>
                </DialogContent>
            </Dialog>

            {/* Delete Modal */}
            <Dialog open={showDeleteModal} onOpenChange={setShowDeleteModal}>
                <DialogContent>
                    <DialogHeader>
                        <DialogTitle>Hapus Cabang</DialogTitle>
                        <DialogDescription>
                            Apakah Anda yakin ingin menghapus cabang ini?
                            {selectedBranch?.members_count &&
                                selectedBranch.members_count > 0 && (
                                    <p className="mt-2 font-medium text-destructive">
                                        Cabang ini memiliki{' '}
                                        {selectedBranch.members_count} anggota.
                                        Tidak dapat dihapus.
                                    </p>
                                )}
                            {selectedBranch?.savings_count &&
                                selectedBranch.savings_count > 0 && (
                                    <p className="mt-2 font-medium text-destructive">
                                        Cabang ini memiliki{' '}
                                        {selectedBranch.savings_count} rekening
                                        simpanan. Tidak dapat dihapus.
                                    </p>
                                )}
                            {selectedBranch?.financings_count &&
                                selectedBranch.financings_count > 0 && (
                                    <p className="mt-2 font-medium text-destructive">
                                        Cabang ini memiliki{' '}
                                        {selectedBranch.financings_count}{' '}
                                        pembiayaan aktif. Tidak dapat dihapus.
                                    </p>
                                )}
                            {selectedBranch?.users_count &&
                                selectedBranch.users_count > 0 && (
                                    <p className="mt-2 font-medium text-destructive">
                                        Cabang ini memiliki{' '}
                                        {selectedBranch.users_count} pengguna.
                                        Tidak dapat dihapus.
                                    </p>
                                )}
                        </DialogDescription>
                    </DialogHeader>
                    <DialogFooter>
                        <Button
                            variant="outline"
                            onClick={() => setShowDeleteModal(false)}
                        >
                            Batal
                        </Button>
                        <Button
                            variant="destructive"
                            onClick={handleConfirmDelete}
                            disabled={
                                (selectedBranch?.members_count || 0) > 0 ||
                                (selectedBranch?.savings_count || 0) > 0 ||
                                (selectedBranch?.financings_count || 0) > 0 ||
                                (selectedBranch?.users_count || 0) > 0
                            }
                        >
                            Hapus
                        </Button>
                    </DialogFooter>
                </DialogContent>
            </Dialog>
        </AppLayout>
    );
}
