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 Expense = {
    id: number;
    amount: number;
    description: string;
    receipt_key: string | null;
    receipt_url: string | null;
    created_at: string;
    created_by: {
        user_profile: {
            full_name: string;
        };
    };
};

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',
    });
}

type CreateColumnsParams = {
    handleEdit: (expense: Expense) => void;
    handleDeleteClick: (expense: Expense) => void;
};

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}
            />
        </>
    );
}

export function createExpenseColumns(
    params: CreateColumnsParams,
): ColumnDef<Expense>[] {
    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>
            ),
        },
        {
            accessorKey: 'description',
            header: () => <span>Keterangan</span>,
            cell: ({ row }) => (
                <span className="max-w-[200px] truncate block">{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} />;
            },
        },
        {
            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 }) => (
                <span className="text-red-600 font-medium">
                    - {formatCurrency(row.getValue('amount') as number)}
                </span>
            ),
        },
        {
            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 expense = row.original;

                return (
                    <TooltipProvider>
                        <div className="flex items-center justify-center gap-1">
                            <Tooltip>
                                <TooltipTrigger asChild>
                                    <Button
                                        variant="ghost"
                                        size="icon"
                                        onClick={() =>
                                            handleEdit(expense)
                                        }
                                    >
                                        <Pencil className="h-4 w-4" />
                                    </Button>
                                </TooltipTrigger>
                                <TooltipContent side="top">
                                    Edit
                                </TooltipContent>
                            </Tooltip>

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