import { RowActions } from '@/components/data-display';
import { ImagePreviewButton } from '@/components/dialogs';
import type { ColumnDef } from '@tanstack/react-table';
import { Pencil, Trash2 } from 'lucide-react';

export type CashTransaction = {
    id: number;
    amount: number;
    formatted_amount: string;
    balance_after: number;
    formatted_balance_after: string;
    type: 'deposit' | 'withdrawal' | 'expense' | 'transfer';
    description: string;
    receipt_key: string | null;
    receipt_url: string | null;
    receipt_conversion_url: string | null;
    created_at: string;
    formatted_created_at: string;
    created_by: {
        user_profile: {
            full_name: string;
        };
    };
    reference: {
        type: string;
    } | null;
};

function getTypeLabel(type: string): string {
    const labels: Record<string, string> = {
        deposit: 'Deposit',
        withdrawal: 'Withdrawal',
        expense: 'Pengeluaran',
        employee_advance: 'Kasbon',
        salary: 'Gaji',
        transaction: 'Transaksi'
    };

    return labels[type] ?? type;
}

type CreateColumnsParams = {
    handleEdit: (transaction: CashTransaction) => void;
    handleDeleteClick: (transaction: CashTransaction) => void;
    can: (permission: string) => boolean;
};

export function createTransactionColumns(
    params: CreateColumnsParams,
): ColumnDef<CashTransaction>[] {
    const { handleEdit, handleDeleteClick, can } = params;

    const columns: ColumnDef<CashTransaction>[] = [
        {
            accessorKey: 'formatted_created_at',
            header: () => <span>Tanggal</span>,
            cell: ({ row }) => (
                <span>{row.getValue('formatted_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>
                    </div>
                );
            },
        },
        {
            accessorKey: 'formatted_amount',
            header: () => <span>Jumlah</span>,
            cell: ({ row }) => {
                const transaction = row.original;
                const isDeposit = transaction.type === 'deposit' || transaction.type === 'transaction';

                return (
                    <span
                        className={
                            isDeposit
                                ? 'foknt-medium text-green-600'
                                : 'font-medium text-red-600'
                        }
                    >
                        {isDeposit ? '+' : '-'}{' '}
                        {row.getValue('formatted_amount') as string}
                    </span>
                );
            },
        },
        {
            accessorKey: 'formatted_balance_after',
            header: () => <span>Saldo Setelah</span>,
            cell: ({ row }) => (
                <span className="font-medium">
                    {row.getValue('formatted_balance_after') as string}
                </span>
            ),
        },
        {
            accessorKey: 'description',
            header: () => <span>Keterangan</span>,
            cell: ({ row }) => (
                <span className="block max-w-[200px]">
                    {row.getValue('description') as string}
                </span>
            ),
        },
        {
            id: 'receipt',
            header: () => <span>Bukti</span>,
            cell: ({ row }) => {
                const receiptConversionUrl = row.original.receipt_conversion_url;
                const receiptUrl = row.original.receipt_url;

                if (!receiptConversionUrl) {
                    return <span className="text-muted-foreground">-</span>;
                }

                return (
                    <ImagePreviewButton
                        srcs={[receiptConversionUrl]}
                        modalSrc={receiptUrl ?? undefined}
                        title={row.original.description}
                    />
                );
            },
        },
        {
            id: 'created_by',
            header: () => <span>Oleh</span>,
            cell: ({ row }) => {
                const createdBy = row.original.created_by;

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

    if (can('cash.update') || can('cash.delete')) {
        columns.push({
            id: 'actions',
            header: () => <span className="block text-center">Aksi</span>,
            meta: {
                className: 'w-[100px] text-center',
                headerClassName: 'w-[100px] text-center',
            },
            cell: ({ row }) => {
                const transaction = row.original;
                const canEdit =
                    transaction.type === 'deposit' ||
                    transaction.type === 'withdrawal';

                if (!canEdit) {
                    return <span className="block text-center">-</span>;
                }

                return (
                    <RowActions
                        actions={[
                            {
                                label: 'Edit',
                                icon: <Pencil className="h-4 w-4" />,
                                show: can('cash.update'),
                                onClick: () => handleEdit(transaction),
                            },
                            {
                                label: 'Hapus',
                                icon: (
                                    <Trash2 className="h-4 w-4 text-destructive" />
                                ),
                                show: can('cash.delete'),
                                onClick: () => handleDeleteClick(transaction),
                            },
                        ]}
                    />
                );
            },
        });
    }

    return columns;
}
