import type { ColumnDef } from '@tanstack/react-table';
import { ArrowUpDown, CircleDollarSign, Pencil, Trash2, XCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
    Tooltip,
    TooltipContent,
    TooltipProvider,
    TooltipTrigger,
} from '@/components/ui/tooltip';
import { formatCurrency } from '@/lib/utils';

export type Payroll = {
    id: number;
    base_salary: number;
    bonus_amount: number;
    deduction_amount: number;
    total_amount: number;
    status: 'unpaid' | 'paid' | 'cancelled';
    paid_at: string | null;
    employee: {
        user: {
            user_profile: {
                full_name: string;
            };
        };
    };
    payroll_adjustments?: PayrollAdjustment[];
};

export type PayrollAdjustment = {
    id: number;
    type: 'bonus' | 'deduction';
    amount: number;
    description: string;
    created_at: string;
};

function getStatusBadge(status: string) {
    const statusConfig: Record<string, { label: string; className: string }> = {
        unpaid: {
            label: 'Belum Dibayar',
            className: 'bg-yellow-100 text-yellow-800 hover:bg-yellow-100',
        },
        paid: {
            label: 'Dibayar',
            className: 'bg-green-100 text-green-800 hover:bg-green-100',
        },
        cancelled: {
            label: 'Dibatalkan',
            className: 'bg-red-100 text-red-800 hover:bg-red-100',
        },
    };

    const config = statusConfig[status] ?? statusConfig.unpaid;

    return (
        <Badge variant="secondary" className={config.className}>
            {config.label}
        </Badge>
    );
}

type CreateColumnsParams = {
    handlePay: (payroll: Payroll) => void;
    handleCancel: (payroll: Payroll) => void;
    handleAddAdjustment: (payroll: Payroll) => void;
    handleDeleteAdjustment: (adjustment: PayrollAdjustment, payrollId: number) => void;
};

export function createPayrollColumns(
    params: CreateColumnsParams,
): ColumnDef<Payroll>[] {
    const { handlePay, handleCancel, handleAddAdjustment, handleDeleteAdjustment } = 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',
            },
        },
        {
            id: 'employee_name',
            header: () => <span>Nama Karyawan</span>,
            cell: ({ row }) => {
                const employee = row.original.employee;

                return <span className="font-medium">{employee?.user?.user_profile?.full_name ?? '-'}</span>;
            },
        },
        {
            accessorKey: 'base_salary',
            header: ({ column }) => (
                <Button
                    variant="ghost"
                    className="-ml-3 h-8"
                    onClick={() =>
                        column.toggleSorting(
                            column.getIsSorted() === 'asc',
                        )
                    }
                >
                    <span>Gaji Pokok</span>
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                </Button>
            ),
            cell: ({ row }) => (
                <span>{formatCurrency(row.getValue('base_salary') as number)}</span>
            ),
        },
        {
            accessorKey: 'bonus_amount',
            header: ({ column }) => (
                <Button
                    variant="ghost"
                    className="-ml-3 h-8"
                    onClick={() =>
                        column.toggleSorting(
                            column.getIsSorted() === 'asc',
                        )
                    }
                >
                    <span>Bonus</span>
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                </Button>
            ),
            cell: ({ row }) => {
                const value = row.getValue('bonus_amount') as number;

                return (
                    <span className={value > 0 ? 'text-green-600 font-medium' : ''}>
                        {value > 0 ? '+ ' : ''}{formatCurrency(value)}
                    </span>
                );
            },
        },
        {
            accessorKey: 'deduction_amount',
            header: ({ column }) => (
                <Button
                    variant="ghost"
                    className="-ml-3 h-8"
                    onClick={() =>
                        column.toggleSorting(
                            column.getIsSorted() === 'asc',
                        )
                    }
                >
                    <span>Potongan</span>
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                </Button>
            ),
            cell: ({ row }) => {
                const value = row.getValue('deduction_amount') as number;

                return (
                    <span className={value > 0 ? 'text-red-600 font-medium' : ''}>
                        {value > 0 ? '- ' : ''}{formatCurrency(value)}
                    </span>
                );
            },
        },
        {
            accessorKey: 'total_amount',
            header: ({ column }) => (
                <Button
                    variant="ghost"
                    className="-ml-3 h-8"
                    onClick={() =>
                        column.toggleSorting(
                            column.getIsSorted() === 'asc',
                        )
                    }
                >
                    <span>Total</span>
                    <ArrowUpDown className="ml-2 h-4 w-4" />
                </Button>
            ),
            cell: ({ row }) => (
                <span className="font-semibold">{formatCurrency(row.getValue('total_amount') as number)}</span>
            ),
        },
        {
            accessorKey: 'status',
            header: () => <span>Status</span>,
            cell: ({ row }) => (
                <span>{getStatusBadge(row.getValue('status') as string)}</span>
            ),
        },
        {
            id: 'adjustments',
            header: () => <span>Penyesuaian</span>,
            cell: ({ row }) => {
                const payroll = row.original;
                const adjustments = payroll.payroll_adjustments ?? [];

                if (adjustments.length === 0) {
                    return <span className="text-muted-foreground">-</span>;
                }

                return (
                    <div className="flex flex-col gap-1">
                        {adjustments.map((adj: PayrollAdjustment) => (
                            <div key={adj.id} className="flex items-center gap-1 text-xs">
                                <span className={adj.type === 'bonus' ? 'text-green-600' : 'text-red-600'}>
                                    {adj.type === 'bonus' ? '+' : '-'} {formatCurrency(adj.amount)}
                                </span>
                                <span className="text-muted-foreground truncate max-w-[100px]">
                                    {adj.description}
                                </span>
                                {payroll.status === 'unpaid' && (
                                    <button
                                        onClick={() => handleDeleteAdjustment(adj, payroll.id)}
                                        className="text-destructive hover:text-destructive/80"
                                    >
                                        <XCircle className="h-3 w-3" />
                                    </button>
                                )}
                            </div>
                        ))}
                    </div>
                );
            },
        },
        {
            id: 'actions',
            header: () => <span className="block text-center">Aksi</span>,
            meta: {
                className: 'w-[120px] text-center',
                headerClassName: 'w-[120px] text-center',
            },
            cell: ({ row }) => {
                const payroll = row.original;

                return (
                    <TooltipProvider>
                        <div className="flex items-center justify-center gap-1">
                            {payroll.status === 'unpaid' && (
                                <>
                                    <Tooltip>
                                        <TooltipTrigger asChild>
                                            <Button
                                                variant="ghost"
                                                size="icon"
                                                onClick={() => handleAddAdjustment(payroll)}
                                            >
                                                <Pencil className="h-4 w-4" />
                                            </Button>
                                        </TooltipTrigger>
                                        <TooltipContent side="top">
                                            Tambah Adjustment
                                        </TooltipContent>
                                    </Tooltip>

                                    <Tooltip>
                                        <TooltipTrigger asChild>
                                            <Button
                                                variant="ghost"
                                                size="icon"
                                                onClick={() => handlePay(payroll)}
                                            >
                                                <CircleDollarSign className="h-4 w-4 text-green-600" />
                                            </Button>
                                        </TooltipTrigger>
                                        <TooltipContent side="top">
                                            Tandai Dibayar
                                        </TooltipContent>
                                    </Tooltip>

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