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

export type EmployeeAdvancePayment = {
    id: number;
    amount: number;
    formatted_amount: string;
    description: string | null;
    paid_at: string;
    formatted_paid_at: string;
    paid_by: {
        user_profile: {
            full_name: string;
        };
    } | null;
};

export type EmployeeAdvance = {
    id: number;
    amount: number;
    formatted_amount: string;
    paid_amount: number;
    formatted_paid_amount: string;
    remaining_amount: number;
    formatted_remaining_amount: string;
    description: string;
    due_date: string;
    formatted_due_date: string;
    status: 'pending' | 'disbursed' | 'partial' | 'repaid' | 'rejected';
    created_at: string;
    formatted_created_at: string;
    employee: {
        user: {
            id: number;
            user_profile: {
                full_name: string;
            };
        };
    };
    payments: EmployeeAdvancePayment[];
};

function getStatusBadge(status: string) {
    const statusConfig: Record<string, { label: string; className: string }> = {
        pending: {
            label: 'Menunggu',
            className: 'bg-yellow-100 text-yellow-800 hover:bg-yellow-100',
        },
        disbursed: {
            label: 'Dikeluarkan',
            className: 'bg-green-100 text-green-800 hover:bg-green-100',
        },
        partial: {
            label: 'Cicilan',
            className: 'bg-orange-100 text-orange-800 hover:bg-orange-100',
        },
        repaid: {
            label: 'Lunas',
            className: 'bg-blue-100 text-blue-800 hover:bg-blue-100',
        },
        rejected: {
            label: 'Ditolak',
            className: 'bg-red-100 text-red-800 hover:bg-red-100',
        },
    };

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

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

type CreateColumnsParams = {
    handleEdit: (employeeAdvance: EmployeeAdvance) => void;
    handleDeleteClick: (employeeAdvance: EmployeeAdvance) => void;
    handleApprove: (employeeAdvance: EmployeeAdvance) => void;
    handlePay: (employeeAdvance: EmployeeAdvance) => void;
    handleShowPayments: (employeeAdvance: EmployeeAdvance) => void;
    can: (permission: string) => boolean;
    authUserId: number;
};

export function createEmployeeAdvanceColumns(
    params: CreateColumnsParams,
): ColumnDef<EmployeeAdvance>[] {
    const { handleEdit, handleDeleteClick, handleApprove, handlePay, handleShowPayments, can, authUserId } =
        params;

    const columns: ColumnDef<EmployeeAdvance>[] = [
        {
            accessorKey: 'formatted_created_at',
            header: () => <span>Tanggal</span>,
            cell: ({ row }) => (
                <span>{row.getValue('formatted_created_at') as string}</span>
            ),
        },
        {
            id: 'employee_name',
            header: () => <span>Oleh</span>,
            cell: ({ row }) => {
                const employee = row.original.employee;

                return (
                    <span>
                        {employee?.user?.user_profile?.full_name ?? '-'}
                    </span>
                );
            },
        },
        {
            accessorKey: 'formatted_amount',
            header: () => <span>Jumlah</span>,
            cell: ({ row }) => (
                <span className="font-medium">
                    {row.getValue('formatted_amount') as string}
                </span>
            ),
        },
        {
            accessorKey: 'formatted_remaining_amount',
            header: () => <span>Sisa</span>,
            cell: ({ row }) => {
                const employeeAdvance = row.original;

                if (employeeAdvance.status === 'repaid') {
                    return <span className="text-green-600">Lunas</span>;
                }

                return (
                    <span className="font-medium text-orange-600">
                        {row.getValue('formatted_remaining_amount') as string}
                    </span>
                );
            },
        },
        {
            accessorKey: 'description',
            header: () => <span>Keterangan</span>,
            cell: ({ row }) => (
                <span className="block max-w-[200px] truncate">
                    {row.getValue('description') as string}
                </span>
            ),
        },
        {
            accessorKey: 'formatted_due_date',
            header: () => <span>Jatuh Tempo</span>,
            cell: ({ row }) => (
                <span>
                    {row.getValue('formatted_due_date') as string}
                </span>
            ),
        },
        {
            accessorKey: 'status',
            header: () => <span>Status</span>,
            cell: ({ row }) => (
                <span>{getStatusBadge(row.getValue('status') as string)}</span>
            ),
        },
    ];

    if (
        can('employee_advances.verify') ||
        can('employee_advances.pay') ||
        can('employee_advances.view_payments') ||
        can('employee_advances.update') ||
        can('employee_advances.delete')
    ) {
        columns.push({
            id: 'actions',
            header: () => <span className="block text-center">Aksi</span>,
            meta: {
                className: 'w-[150px] text-center',
                headerClassName: 'w-[150px] text-center',
            },
            cell: ({ row }) => {
                const employeeAdvance = row.original;

                return (
                    <RowActions
                        actions={[
                            {
                                label: 'Setujui',
                                icon: (
                                    <CheckCircle className="h-4 w-4 text-green-600" />
                                ),
                                show:
                                    can('employee_advances.verify') &&
                                    employeeAdvance.status === 'pending',
                                onClick: () => handleApprove(employeeAdvance),
                            },
                            {
                                label: 'Bayar',
                                icon: (
                                    <CircleDollarSign className="h-4 w-4 text-blue-600" />
                                ),
                                show:
                                    can('employee_advances.pay') &&
                                    (employeeAdvance.status === 'disbursed' || employeeAdvance.status === 'partial'),
                                onClick: () => handlePay(employeeAdvance),
                            },
                            {
                                label: 'Riwayat',
                                icon: <History className="h-4 w-4" />,
                                show: can('employee_advances.view_payments') && employeeAdvance.payments.length > 0,
                                onClick: () => handleShowPayments(employeeAdvance),
                            },
                            {
                                label: 'Edit',
                                icon: <Pencil className="h-4 w-4" />,
                                show:
                                    can('employee_advances.update') &&
                                    employeeAdvance.status === 'pending' &&
                                    employeeAdvance.employee?.user?.id === authUserId,
                                onClick: () => handleEdit(employeeAdvance),
                            },
                            {
                                label: 'Hapus',
                                icon: (
                                    <Trash2 className="h-4 w-4 text-destructive" />
                                ),
                                show:
                                    can('employee_advances.delete') &&
                                    employeeAdvance.status === 'pending' &&
                                    employeeAdvance.employee?.user?.id === authUserId,
                                onClick: () =>
                                    handleDeleteClick(employeeAdvance),
                            },
                        ]}
                    />
                );
            },
        });
    }

    return columns;
}
