import { ImagePreviewModal } from '@/components/image-preview-modal';
import { Button } from '@/components/ui/button';
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import { formatCurrency } from '@/lib/utils';
import type { ColumnDef } from '@tanstack/react-table';
import { ArrowUpDown, Pencil, Trash2 } from 'lucide-react';
import { useState } from 'react';

export type CashTransaction = {
    id: number;
    amount: number;
    balance_after: number;
    type: 'deposit' | 'withdrawal' | 'expense' | 'transfer';
    description: string;
    receipt_key: string | null;
    receipt_url: string | null;
    created_at: string;
    created_by: {
        user_profile: {
            full_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] ?? '-';
}

function ReceiptPreview({ url, title }: { url: string; title: string }) {
    const [open, setOpen] = useState(false);

    return (
        <>
            <button
                onClick={() => setOpen(true)}
                className="block h-10 w-10 overflow-hidden rounded-md border bg-muted transition-opacity hover:opacity-80"
            >
                <img
                    src={url}
                    alt={title}
                    className="h-full w-full object-cover"
                />
            </button>
            <ImagePreviewModal
                open={open}
                onOpenChange={setOpen}
                src={url}
                title={title}
            />
        </>
    );
}

type CreateColumnsParams = {
    handleEdit: (transaction: CashTransaction) => void;
    handleDeleteClick: (transaction: CashTransaction) => void;
};

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

    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
                                ? 'font-medium text-green-600'
                                : 'font-medium text-red-600'
                        }
                    >
                        {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="block max-w-[200px] truncate">
                    {row.getValue('description') as string}
                </span>
            ),
        },
        {
            id: 'receipt',
            header: () => <span>Bukti</span>,
            cell: ({ row }) => {
                const receiptUrl = row.original.receipt_url;

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

                return (
                    <ReceiptPreview
                        url={receiptUrl}
                        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>;
            },
        },
        {
            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 (
                    <TooltipProvider>
                        <div className="flex items-center justify-center gap-1">
                            <Tooltip>
                                <TooltipTrigger asChild>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        onClick={() => handleEdit(transaction)}
                                    >
                                        <Pencil className="h-4 w-4" />
                                    </Button>
                                </TooltipTrigger>
                                <TooltipContent side="top">Edit</TooltipContent>
                            </Tooltip>

                            <Tooltip>
                                <TooltipTrigger asChild>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        onClick={() =>
                                            handleDeleteClick(transaction)
                                        }
                                    >
                                        <Trash2 className="h-4 w-4 text-destructive" />
                                    </Button>
                                </TooltipTrigger>
                                <TooltipContent side="top">
                                    Hapus
                                </TooltipContent>
                            </Tooltip>
                        </div>
                    </TooltipProvider>
                );
            },
        },
    ];
}
