import { Badge } from '@ui/components/ui/badge';
import { Button } from '@ui/components/ui/button';
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from '@ui/components/ui/tooltip';
import { ChevronDown, ChevronRight, Plus, Pencil, Trash2 } from 'lucide-react';
import { useState } from 'react';
import { useAppText } from '@/lib/app-text';
import type { ChartOfAccount } from '@/types/finance';

interface AccountTreeRowProps {
    account: ChartOfAccount;
    level: number;
    onEdit: (account: ChartOfAccount) => void;
    onDelete: (account: ChartOfAccount) => void;
    onAddChild: (parentAccount: ChartOfAccount) => void;
}

const getAccountChildren = (account: ChartOfAccount): ChartOfAccount[] => {
    const maybeChildren = (account as any).children;

    if (Array.isArray(maybeChildren)) {
        return maybeChildren;
    }

    if (maybeChildren && Array.isArray(maybeChildren.data)) {
        return maybeChildren.data;
    }

    return [];
};

export function AccountTreeRow({ account, level, onEdit, onDelete, onAddChild }: AccountTreeRowProps) {
    const { t: text } = useAppText();
    const [isExpanded, setIsExpanded] = useState(level === 0);
    const children = getAccountChildren(account);
    const hasChildren = children.length > 0;

    const paddingLeft = `${level * 2}rem`;

    return (
        <>
            <tr className="border-b hover:bg-muted/50">
                <td className="p-3" style={{ paddingLeft }}>
                    <div className="flex items-center gap-2">
                        {hasChildren ? (
                            <button
                                onClick={() => setIsExpanded(!isExpanded)}
                                className="p-1 hover:bg-muted rounded"
                            >
                                {isExpanded ? (
                                    <ChevronDown className="h-4 w-4" />
                                ) : (
                                    <ChevronRight className="h-4 w-4" />
                                )}
                            </button>
                        ) : (
                            <div className="w-6" />
                        )}
                        <span className="font-mono text-sm">{account.code}</span>
                    </div>
                </td>
                <td className="p-3">
                    <span className="font-medium">{account.name}</span>
                </td>
                <td className="p-3">
                    <Badge variant="outline">{account.type_label}</Badge>
                </td>
                <td className="p-3">
                    <Badge variant={account.normal_balance === 'debit' ? 'default' : 'secondary'}>
                        {account.normal_balance_label}
                    </Badge>
                </td>
                <td className="p-3">
                    <Badge variant={account.is_active ? 'default' : 'secondary'}>
                        {account.is_active ? text('common.status_active') : text('common.status_inactive')}
                    </Badge>
                </td>
                <td className="p-3">
                    <div className="flex items-center gap-1">
                        <TooltipProvider>
                            <Tooltip>
                                <TooltipTrigger asChild>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-8 w-8"
                                        onClick={() => onAddChild(account)}
                                    >
                                        <Plus className="h-4 w-4" />
                                        <span className="sr-only">{text('chart_of_account.btn_add_child')}</span>
                                    </Button>
                                </TooltipTrigger>
                                <TooltipContent>
                                    <p>{text('chart_of_account.btn_add_child')}</p>
                                </TooltipContent>
                            </Tooltip>
                        </TooltipProvider>

                        <TooltipProvider>
                            <Tooltip>
                                <TooltipTrigger asChild>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-8 w-8"
                                        onClick={() => onEdit(account)}
                                    >
                                        <Pencil className="h-4 w-4" />
                                        <span className="sr-only">{text('common.btn_edit')}</span>
                                    </Button>
                                </TooltipTrigger>
                                <TooltipContent>
                                    <p>{text('common.btn_edit')}</p>
                                </TooltipContent>
                            </Tooltip>
                        </TooltipProvider>

                        <TooltipProvider>
                            <Tooltip>
                                <TooltipTrigger asChild>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        className="h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10"
                                        onClick={() => onDelete(account)}
                                    >
                                        <Trash2 className="h-4 w-4" />
                                        <span className="sr-only">{text('common.btn_delete')}</span>
                                    </Button>
                                </TooltipTrigger>
                                <TooltipContent>
                                    <p>{text('common.btn_delete')}</p>
                                </TooltipContent>
                            </Tooltip>
                        </TooltipProvider>
                    </div>
                </td>
            </tr>

            {/* Render children if expanded */}
            {isExpanded && hasChildren && children.map((child) => (
                <AccountTreeRow
                    key={child.id}
                    account={child}
                    level={level + 1}
                    onEdit={onEdit}
                    onDelete={onDelete}
                    onAddChild={onAddChild}
                />
            ))}
        </>
    );
}

interface AccountTreeTableProps {
    accounts: ChartOfAccount[];
    onEdit: (account: ChartOfAccount) => void;
    onDelete: (account: ChartOfAccount) => void;
    onAddChild: (parentAccount: ChartOfAccount) => void;
}

export function AccountTreeTable({ accounts, onEdit, onDelete, onAddChild }: AccountTreeTableProps) {
    const { t: text } = useAppText();

    return (
        <div className="rounded-md border">
            <table className="w-full text-foreground">
                <thead className="bg-muted/50">
                    <tr className="border-b">
                        <th className="p-3 text-left font-medium text-foreground">{text('chart_of_account.field_code')}</th>
                        <th className="p-3 text-left font-medium text-foreground">{text('chart_of_account.field_name')}</th>
                        <th className="p-3 text-left font-medium text-foreground">{text('chart_of_account.field_type')}</th>
                        <th className="p-3 text-left font-medium text-foreground">{text('chart_of_account.field_balance')}</th>
                        <th className="p-3 text-left font-medium text-foreground">{text('common.label_active_status')}</th>
                        <th className="p-3 text-left font-medium text-foreground">{text('common.label_actions')}</th>
                    </tr>
                </thead>
                <tbody className="text-foreground">
                    {accounts.length === 0 ? (
                        <tr>
                            <td colSpan={6} className="p-8 text-center text-muted-foreground">
                                {text('common.msg_no_data')}
                            </td>
                        </tr>
                    ) : (
                        accounts.map((account) => (
                            <AccountTreeRow
                                key={account.id}
                                account={account}
                                level={0}
                                onEdit={onEdit}
                                onDelete={onDelete}
                                onAddChild={onAddChild}
                            />
                        ))
                    )}
                </tbody>
            </table>
        </div>
    );
}

