import { Head, router } from '@inertiajs/react';
import { Button } from '@ui/components/ui/button';
import { Input } from '@ui/components/ui/input';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@ui/components/ui/select';
import { Plus, Filter } 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 { useAppText } from '@/lib/app-text';
import type { ChartOfAccount, ChartOfAccountFormData } from '@/types/finance';
import { AccountTreeTable } from './components/AccountTreeTable';
import { ChartOfAccountForm } from './components/ChartOfAccountForm';

interface ChartOfAccountIndexProps {
    title: string;
    accounts: ChartOfAccount[];
    filters?: {
        type?: string;
        is_active?: string;
        search?: string;
    };
}

export default function ChartOfAccountIndex({ title, accounts, filters }: ChartOfAccountIndexProps) {
    const { t: text } = useAppText();

    const [isDrawerOpen, setIsDrawerOpen] = useState(false);
    const [selectedAccount, setSelectedAccount] = useState<ChartOfAccount | undefined>();
    const [parentAccount, setParentAccount] = useState<ChartOfAccount | undefined>();
    const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
    const [accountToDelete, setAccountToDelete] = useState<ChartOfAccount | undefined>();
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [isDeleting, setIsDeleting] = useState(false);

    // Filters
    const [typeFilter, setTypeFilter] = useState(filters?.type || '');
    const [activeFilter, setActiveFilter] = useState(filters?.is_active || '');
    const [searchQuery, setSearchQuery] = useState(filters?.search || '');

    const handleCreate = () => {
        setSelectedAccount(undefined);
        setParentAccount(undefined);
        setIsDrawerOpen(true);
    };

    const handleAddChild = (parent: ChartOfAccount) => {
        setSelectedAccount(undefined);
        setParentAccount(parent);
        setIsDrawerOpen(true);
    };

    const handleEdit = (account: ChartOfAccount) => {
        setSelectedAccount(account);
        setParentAccount(undefined);
        setIsDrawerOpen(true);
    };

    const handleDeleteClick = (account: ChartOfAccount) => {
        setAccountToDelete(account);
        setIsDeleteDialogOpen(true);
    };

    const handleSubmit = (data: ChartOfAccountFormData) => {
        const payload: ChartOfAccountFormData = {
            ...data,
            parent_id: parentAccount ? parentAccount.id : data.parent_id,
        };

        const showSubmitError = (errors?: Record<string, string>) => {
            const firstError = errors ? Object.values(errors)[0] : undefined;
            toast.error(firstError || text('common.msg_error'));
        };

        if (selectedAccount) {
            router.put(`/department/finance/chart-of-account/${selectedAccount.id}`, payload as any, {
                onStart: () => setIsSubmitting(true),
                onSuccess: () => {
                    toast.success(text('common.msg_success_update', { module: text('chart_of_account.title') }));
                    setIsDrawerOpen(false);
                },
                onError: (errors) => {
                    showSubmitError(errors as Record<string, string>);
                },
                onFinish: () => setIsSubmitting(false),
            });
        } else {
            router.post('/department/finance/chart-of-account', payload as any, {
                onStart: () => setIsSubmitting(true),
                onSuccess: () => {
                    toast.success(text('common.msg_success_create', { module: text('chart_of_account.title') }));
                    setIsDrawerOpen(false);
                },
                onError: (errors) => {
                    showSubmitError(errors as Record<string, string>);
                },
                onFinish: () => setIsSubmitting(false),
            });
        }
    };

    const handleDeleteConfirm = async () => {
        if (!accountToDelete) {
return;
}

        setIsDeleting(true);

        router.delete(`/department/finance/chart-of-account/${accountToDelete.id}`, {
            onSuccess: () => {
                toast.success(text('common.msg_success_delete', { module: text('chart_of_account.title') }));
                setIsDeleteDialogOpen(false);
                setAccountToDelete(undefined);
            },
            onError: () => {
                toast.error(text('common.msg_error'));
            },
            onFinish: () => setIsDeleting(false),
        });
    };

    const handleFilterChange = () => {
        router.get('/department/finance/chart-of-account', {
            type: typeFilter || undefined,
            is_active: activeFilter || undefined,
            search: searchQuery || undefined,
        }, {
            preserveState: true,
            preserveScroll: true,
        });
    };

    const handleResetFilters = () => {
        setTypeFilter('');
        setActiveFilter('');
        setSearchQuery('');
        router.get('/department/finance/chart-of-account');
    };

    return (
        <FinanceAppLayout>
            <Head title={title || text('chart_of_account.title')} />

            <div className="flex h-full flex-1 flex-col gap-4 p-4">
                {/* Header */}
                <div className="flex items-center justify-between">
                    <div>
                        <h1 className="text-2xl font-bold tracking-tight text-foreground">{text('chart_of_account.title')}</h1>
                        <p className="text-muted-foreground">
                            {text('chart_of_account.description')}
                        </p>
                    </div>
                    <Button onClick={handleCreate}>
                        <Plus className="mr-2 h-4 w-4" />
                        {text('common.btn_create')}
                    </Button>
                </div>

                {/* Filters */}
                <div className="flex gap-4 items-end">
                    <div className="flex-1">
                        <label className="mb-2 block text-sm font-medium text-foreground">{text('common.label_search')}</label>
                        <Input
                            placeholder={text('common.label_search')}
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            onKeyDown={(e) => e.key === 'Enter' && handleFilterChange()}
                        />
                    </div>
                    <div className="w-48">
                        <label className="mb-2 block text-sm font-medium text-foreground">{text('chart_of_account.field_type')}</label>
                        <Select value={typeFilter} onValueChange={setTypeFilter}>
                            <SelectTrigger>
                                <SelectValue placeholder={text('common.label_filter')} />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="asset">{text('chart_of_account.types.asset')}</SelectItem>
                                <SelectItem value="liability">{text('chart_of_account.types.liability')}</SelectItem>
                                <SelectItem value="equity">{text('chart_of_account.types.equity')}</SelectItem>
                                <SelectItem value="revenue">{text('chart_of_account.types.revenue')}</SelectItem>
                                <SelectItem value="expense">{text('chart_of_account.types.expense')}</SelectItem>
                            </SelectContent>
                        </Select>
                    </div>
                    <div className="w-48">
                        <label className="mb-2 block text-sm font-medium text-foreground">{text('common.label_active_status')}</label>
                        <Select value={activeFilter} onValueChange={setActiveFilter}>
                            <SelectTrigger>
                                <SelectValue placeholder={text('common.label_filter')} />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectItem value="1">{text('common.status_active')}</SelectItem>
                                <SelectItem value="0">{text('common.status_inactive')}</SelectItem>
                            </SelectContent>
                        </Select>
                    </div>
                    <Button variant="outline" onClick={handleFilterChange} className="text-foreground">
                        <Filter className="mr-2 h-4 w-4" />
                        {text('common.label_filter')}
                    </Button>
                    <Button variant="outline" className="text-foreground" onClick={handleResetFilters}>
                        {text('common.btn_reset')}
                    </Button>
                </div>

                {/* Tree Table */}
                <AccountTreeTable
                    accounts={accounts}
                    onEdit={handleEdit}
                    onDelete={handleDeleteClick}
                    onAddChild={handleAddChild}
                />
            </div>

            {/* Create/Edit Drawer */}
            <ResizableDrawer
                open={isDrawerOpen}
                onOpenChange={setIsDrawerOpen}
                title={
                    selectedAccount
                        ? text('chart_of_account.edit_title')
                        : parentAccount
                            ? text('chart_of_account.create_title') + ` (${parentAccount.code})`
                            : text('chart_of_account.create_title')
                }
                description={
                    selectedAccount
                        ? text('drawer.edit_description', { module: text('chart_of_account.title').toLowerCase() })
                        : text('drawer.create_description', { module: text('chart_of_account.title').toLowerCase() })
                }
            >
                <ChartOfAccountForm
                    account={selectedAccount}
                    parentAccount={parentAccount}
                    onSubmit={handleSubmit}
                    isSubmitting={isSubmitting}
                    onCancel={() => setIsDrawerOpen(false)}
                />
            </ResizableDrawer>

            <DeleteConfirmationDialog
                open={isDeleteDialogOpen}
                onOpenChange={setIsDeleteDialogOpen}
                onConfirm={handleDeleteConfirm}
                   title={text('dialog.delete_title', { module: text('chart_of_account.title') })}
                itemName={accountToDelete?.name}
                isDeleting={isDeleting}
            />
        </FinanceAppLayout>
    );
}

