import type { ColumnDef } from '@tanstack/react-table';
import { CircleDollarSign, Pencil, Trash2, XCircle } from 'lucide-react';
import { RowActions } from '@/components/data-display';
import { Badge } from '@/components/ui/badge';
import { formatCurrency } from '@/lib/utils';

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

export type PayrollAdjustment = {
    id: number;
    created_by_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;
    can: (permission: string) => boolean;
    hasAnyRole: (roles: string[]) => boolean;
    userId: number;
};

export function createPayrollColumns(
    params: CreateColumnsParams,
): ColumnDef<Payroll>[] {
    const {
        handlePay,
        handleCancel,
        handleAddAdjustment,
        handleDeleteAdjustment,
        can,
        hasAnyRole,
        userId,
    } = params;

    const hasAnyPayrollAction = can('payroll.adjust') || can('payroll.pay') || can('payroll.cancel');

    const columns: ColumnDef<Payroll>[] = [
        {
            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: 'formatted_base_salary',
            header: () => <span>Gaji Pokok</span>,
            cell: ({ row }) => (
                <span>
                    {row.getValue('formatted_base_salary') as string}
                </span>
            ),
        },
        {
            accessorKey: 'formatted_bonus_amount',
            header: () => <span>Bonus</span>,
            cell: ({ row }) => {
                const value = row.original.bonus_amount;

                return (
                    <span
                        className={
                            value > 0 ? 'font-medium text-green-600' : ''
                        }
                    >
                        {value > 0 ? '+ ' : ''}
                        {row.getValue('formatted_bonus_amount') as string}
                    </span>
                );
            },
        },
        {
            accessorKey: 'formatted_deduction_amount',
            header: () => <span>Potongan</span>,
            cell: ({ row }) => {
                const value = row.original.deduction_amount;

                return (
                    <span
                        className={value > 0 ? 'font-medium text-red-600' : ''}
                    >
                        {value > 0 ? '- ' : ''}
                        {row.getValue('formatted_deduction_amount') as string}
                    </span>
                );
            },
        },
        {
            accessorKey: 'formatted_total_amount',
            header: () => <span>Total</span>,
            cell: ({ row }) => (
                <span className="font-semibold">
                    {row.getValue('formatted_total_amount') as string}
                </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="max-w-[100px] text-muted-foreground">
                                    {adj.description}
                                </span>
                                {can('payroll.adjust') && payroll.status === 'unpaid' && (adj.created_by_id === userId || hasAnyRole(['developer', 'owner'])) && (
                                    <button
                                        onClick={() =>
                                            handleDeleteAdjustment(
                                                adj,
                                                payroll.id,
                                            )
                                        }
                                        className="text-destructive hover:text-destructive/80"
                                    >
                                        <XCircle className="h-3 w-3" />
                                    </button>
                                )}
                            </div>
                        ))}
                    </div>
                );
            },
        },
    ];

    if (hasAnyPayrollAction) {
        columns.push({
            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 (
                    <RowActions
                        actions={[
                            {
                                label: 'Tambah Adjustment',
                                icon: <Pencil className="h-4 w-4" />,
                                show:
                                    can('payroll.adjust') &&
                                    payroll.status === 'unpaid',
                                onClick: () => handleAddAdjustment(payroll),
                            },
                            {
                                label: 'Tandai Dibayar',
                                icon: (
                                    <CircleDollarSign className="h-4 w-4 text-green-600" />
                                ),
                                show:
                                    can('payroll.pay') &&
                                    payroll.status === 'unpaid',
                                onClick: () => handlePay(payroll),
                            },
                            {
                                label: 'Batalkan',
                                icon: (
                                    <XCircle className="h-4 w-4 text-destructive" />
                                ),
                                show:
                                    can('payroll.cancel') &&
                                    payroll.status === 'unpaid',
                                onClick: () => handleCancel(payroll),
                            },
                        ]}
                    />
                );
            },
        });
    }

    return columns;
}
