import { Head, router } from '@inertiajs/react';
import { ServerDataTable } from '@ui/components/data-table/server-data-table';
import { Button } from '@ui/components/ui/button';
import { Plus } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import { DeleteConfirmationDialog } from '@/components/common/DeleteConfirmationDialog';
import { ResizableDrawer } from '@/components/common/ResizableDrawer';
import { FinanceAppLayout } from '@/layouts/finance-app-layout';
import type { SourceAccount, SourceAccountFormData } from '@/types/finance';
import { createSourceAccountColumns } from './Columns';
import { SourceAccountForm } from './components/SourceAccountForm';

interface SourceAccountIndexProps {
    title: string;
}

export default function SourceAccountIndex({ title }: SourceAccountIndexProps) {
    const moduleTitle = 'Akun Sumber';
    const moduleDescription = 'Kelola daftar akun sumber untuk kebutuhan anggaran dan pelaporan.';
    // UI state
    const [isDrawerOpen, setIsDrawerOpen] = useState(false);
    const [selectedSourceAccount, setSelectedSourceAccount] = useState<SourceAccount | undefined>();
    const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
    const [sourceAccountToDelete, setSourceAccountToDelete] = useState<SourceAccount | undefined>();
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isDeleting, setIsDeleting] = useState(false);
    const [refreshKey, setRefreshKey] = useState(0);

    const getFirstErrorMessage = (
        errors?: Record<string, string | string[]>
    ): string | undefined => {
        if (!errors) {
            return undefined;
        }

        for (const value of Object.values(errors)) {
            if (Array.isArray(value) && value.length > 0) {
                return value[0];
            }

            if (typeof value === 'string' && value.trim().length > 0) {
                return value;
            }
        }

        return undefined;
    };

    const showSubmitError = (errors?: Record<string, string | string[]>) => {
        const firstError = getFirstErrorMessage(errors);
        toast.error(firstError || 'Terjadi kesalahan. Silakan coba lagi.');
    };

    // Handle Create
    const handleCreate = () => {
        setSelectedSourceAccount(undefined);
        setIsDrawerOpen(true);
    };

    // Handle Edit
    const handleEdit = (sourceAccount: SourceAccount) => {
        setSelectedSourceAccount(sourceAccount);
        setIsDrawerOpen(true);
    };

    // Handle Delete Click
    const handleDeleteClick = (sourceAccount: SourceAccount) => {
        setSourceAccountToDelete(sourceAccount);
        setIsDeleteDialogOpen(true);
    };

    // Handle Form Submit
    const handleSubmit = (data: SourceAccountFormData) => {
        if (selectedSourceAccount) {
            // Update
            router.put(`/department/finance/source-account/${selectedSourceAccount.id}`, data as any, {
                preserveState: true,
                preserveScroll: true,
                onStart: () => setIsSubmitting(true),
                onSuccess: () => {
                    toast.success(`${moduleTitle} berhasil diperbarui.`);
                    setIsDrawerOpen(false);
                    setRefreshKey(prev => prev + 1);
                },
                onError: (errors) => {
                    showSubmitError(errors as Record<string, string | string[]>);
                },
                onFinish: () => setIsSubmitting(false),
            });
        } else {
            // Create
            router.post('/department/finance/source-account', data as any, {
                preserveState: true,
                preserveScroll: true,
                onStart: () => setIsSubmitting(true),
                onSuccess: () => {
                    toast.success(`${moduleTitle} berhasil dibuat.`);
                    setIsDrawerOpen(false);
                    setRefreshKey(prev => prev + 1);
                },
                onError: (errors) => {
                    showSubmitError(errors as Record<string, string | string[]>);
                },
                onFinish: () => setIsSubmitting(false),
            });
        }
    };

    // Handle Delete Confirm
    const handleDeleteConfirm = () => {
        if (!sourceAccountToDelete) {
            return;
        }

        router.delete(`/department/finance/source-account/${sourceAccountToDelete.id}`, {
            preserveState: true,
            preserveScroll: true,
            onStart: () => setIsDeleting(true),
            onSuccess: () => {
                toast.success('Akun sumber berhasil dihapus.');
                setIsDeleteDialogOpen(false);
                setSourceAccountToDelete(undefined);
                setRefreshKey(prev => prev + 1);
            },
            onError: () => {
                toast.error('Terjadi kesalahan. Silakan coba lagi.');
            },
            onFinish: () => setIsDeleting(false),
        });
    };

    // Create columns with handlers
    const columns = createSourceAccountColumns({
        onEdit: handleEdit,
        onDelete: handleDeleteClick,
    });

    return (
        <FinanceAppLayout>
            <Head title={title || moduleTitle} />

            <div className="flex h-full flex-1 flex-col gap-4 p-4">
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-2xl font-bold tracking-tight text-foreground">{moduleTitle}</h1>
                        <p className="text-muted-foreground">{moduleDescription}</p>
                    </div>
                    <Button onClick={handleCreate}>
                        <Plus className="mr-2 h-4 w-4" />
                        Tambah Akun Sumber
                    </Button>
                </div>

                <ServerDataTable
                    key={refreshKey}
                    columns={columns as unknown as Record<string, unknown>[]}
                    endpoint="/department/finance/source-account/datatable"
                    searchPlaceholder="Cari akun sumber..."
                    enableGlobalFilter={true}
                    enableSorting={true}
                    enableRowSelection={false}
                    enableColumnVisibility={true}
                    initialPageSize={20}
                />
            </div>

            {/* Create/Edit Drawer */}
            <ResizableDrawer
                open={isDrawerOpen}
                onOpenChange={setIsDrawerOpen}
                title={selectedSourceAccount
                    ? 'Ubah Akun Sumber'
                    : 'Tambah Akun Sumber'}
                description={
                    selectedSourceAccount
                        ? 'Perbarui informasi akun sumber yang dipilih.'
                        : 'Isi formulir untuk menambahkan akun sumber baru.'
                }
            >
                <SourceAccountForm
                    sourceAccount={selectedSourceAccount}
                    onSubmit={handleSubmit}
                    isSubmitting={isSubmitting}
                    onCancel={() => setIsDrawerOpen(false)}
                />
            </ResizableDrawer>

            {/* Delete Confirmation Dialog */}
            <DeleteConfirmationDialog
                open={isDeleteDialogOpen}
                onOpenChange={setIsDeleteDialogOpen}
                onConfirm={handleDeleteConfirm}
                title={`Hapus ${moduleTitle}`}
                itemName={sourceAccountToDelete?.name}
                isDeleting={isDeleting}
            />
        </FinanceAppLayout>
    );
}

