import type { ColumnDef } from '@tanstack/vue-table';
import { h } from 'vue';
import { DataTableColumnHeader } from '@/components/data-table';
import MediaThumbnailCell from '@/components/media/MediaThumbnailCell.vue';
import { Badge } from '@/components/ui/badge';
import type { CashTransactionListItem } from '@/types/cash';
import DataTableActions from './data-table-actions.vue';

export function createColumns(onEdit: (transaction: CashTransactionListItem) => void): ColumnDef<CashTransactionListItem>[] {
    return [
        {
            accessorKey: 'created_at_formatted',
            enableSorting: true,
            header: () => h(DataTableColumnHeader, { title: 'Tanggal', column: 'created_at' }),
        },
        {
            accessorKey: 'reference_label',
            enableSorting: true,
            header: () => h(DataTableColumnHeader, { title: 'Sumber', column: 'reference_type' }),
            cell: ({ row }) => h(
                Badge,
                { class: row.original.source_badge_class },
                () => row.original.reference_label,
            ),
        },
        {
            accessorKey: 'amount_formatted',
            enableSorting: true,
            header: () => h(DataTableColumnHeader, { title: 'Jumlah', column: 'amount' }),
            cell: ({ row }) => {
                const isIncoming = row.original.is_incoming;
                const prefix = isIncoming ? '+' : '-';

                return h(
                    'span',
                    { class: isIncoming ? 'font-medium text-green-600' : 'font-medium text-red-600' },
                    `${prefix} ${row.original.amount_formatted}`,
                );
            },
        },
        {
            accessorKey: 'balance_after_formatted',
            enableSorting: false,
            header: () => 'Saldo Setelah',
        },
        {
            accessorKey: 'description',
            enableSorting: false,
            header: () => 'Keterangan',
        },
        {
            id: 'photos',
            enableSorting: false,
            header: () => 'Foto',
            cell: ({ row }) => h(MediaThumbnailCell, { items: row.original.photos ?? [] }),
        },
        {
            accessorKey: 'created_by_name',
            enableSorting: false,
            header: () => 'Oleh',
        },
        {
            id: 'actions',
            enableSorting: false,
            enableHiding: false,
            cell: ({ row }) => {
                if (row.original.reference_type !== null) {
                    return null;
                }

                return h(DataTableActions, {
                    transaction: row.original,
                    onEdit: () => onEdit(row.original),
                });
            },
        },
    ];
}
