import type { ColumnDef } from '@tanstack/react-table';
import { ArrowUpDown } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { formatCurrency } from '@/lib/utils';

export type CashTransaction = {
    id: number;
    amount: number;
    balance_after: number;
    type: 'deposit' | 'withdrawal' | 'expense' | 'transfer';
    description: string;
    created_at: string;
    created_by: {
        name: string;
    };
    reference: {
        type: string;
    } | null;
};

function formatDate(dateString: string): string {
    const date = new Date(dateString);

    return date.toLocaleDateString('id-ID', {
        day: '2-digit',
        month: 'short',
        year: 'numeric',
    }) + ' ' + date.toLocaleTimeString('id-ID', {
        hour: '2-digit',
        minute: '2-digit',
    });
}

function getTypeLabel(type: string): string {
    const labels: Record<string, string> = {
        deposit: 'Deposit',
        withdrawal: 'Withdrawal',
        expense: 'Pengeluaran',
        transfer: 'Transfer',
    };

    return labels[type] ?? type;
}

function getReferenceLabel(type: string): string {
    const labels: Record<string, string> = {
        'App\\Models\\Expense': 'Pengeluaran',
        'App\\Models\\Order': 'Penjualan Tunai',
        'App\\Models\\Purchase': 'Pembelian',
        'App\\Models\\CashAccount': 'Transfer Kas',
    };

    return labels[type] ?? '-';
}

export function createTransactionColumns(): ColumnDef<CashTransaction>[] {
    return [
        {
            id: 'no',
            header: () => <span className="block text-center">No</span>,
            cell: ({ row }) => (
                <span className="block text-center">
                    {row.index + 1}
                </span>
            ),
            meta: {
                className: 'w-[50px] text-center',
                headerClassName: 'w-[50px] text-center',
            },
        },
        {
            accessorKey: 'created_at',
            header: ({ column }) => (
                <Button
                    variant="ghost"
                    className="-ml-3 h-8"
                    onClick={() =>
                        column.toggleSorting(
                            column.getIsSorted() === 'asc',
                        )
                    }
                >
                    <span>Tanggal</span>
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                </Button>
            ),
            cell: ({ row }) => (
                <span>{formatDate(row.getValue('created_at') as string)}</span>
            ),
        },
        {
            id: 'source',
            header: () => <span>Sumber</span>,
            cell: ({ row }) => {
                const transaction = row.original;

                return (
                    <div className="flex flex-col">
                        <span className="font-medium">{getTypeLabel(transaction.type)}</span>
                        <span className="text-xs text-muted-foreground">{getReferenceLabel(transaction.reference?.type ?? '')}</span>
                    </div>
                );
            },
        },
        {
            accessorKey: 'amount',
            header: ({ column }) => (
                <Button
                    variant="ghost"
                    className="-ml-3 h-8"
                    onClick={() =>
                        column.toggleSorting(
                            column.getIsSorted() === 'asc',
                        )
                    }
                >
                    <span>Jumlah</span>
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                </Button>
            ),
            cell: ({ row }) => {
                const transaction = row.original;
                const isDeposit = transaction.type === 'deposit';

                return (
                    <span className={isDeposit ? 'text-green-600 font-medium' : 'text-red-600 font-medium'}>
                        {isDeposit ? '+' : '-'} {formatCurrency(row.getValue('amount') as number)}
                    </span>
                );
            },
        },
        {
            accessorKey: 'balance_after',
            header: ({ column }) => (
                <Button
                    variant="ghost"
                    className="-ml-3 h-8"
                    onClick={() =>
                        column.toggleSorting(
                            column.getIsSorted() === 'asc',
                        )
                    }
                >
                    <span>Saldo Setelah</span>
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                </Button>
            ),
            cell: ({ row }) => (
                <span className="font-medium">{formatCurrency(row.getValue('balance_after') as number)}</span>
            ),
        },
        {
            accessorKey: 'description',
            header: () => <span>Keterangan</span>,
            cell: ({ row }) => (
                <span className="max-w-[200px] truncate block">{row.getValue('description') as string}</span>
            ),
        },
        {
            id: 'created_by',
            header: () => <span>Oleh</span>,
            cell: ({ row }) => {
                const createdBy = row.original.created_by;
                console.log(createdBy)

                return <span>{createdBy?.user_profile?.full_name ?? '-'}</span>;
            },
        },
    ];
}
