import type { ColumnDef } from '@tanstack/react-table';
import { KeyRound, Pencil, Trash2 } from 'lucide-react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { RowActions } from '@/components/data-display';
import { ToggleStatus } from '@/components/data-display';
import { formatCurrency } from '@/lib/utils';

export type Employee = {
    id: number;
    email: string;
    username: string;
    is_active: boolean;
    photo_url: string | null;
    roles?: { name: string }[];
    user_profile: {
        full_name: string;
        phone_number: string | null;
    } | null;
    employee: {
        join_date: string;
        resign_date: string | null;
        employment_status: string;
        base_salary: number;
    } | null;
};

function getEmploymentStatusLabel(status: string): string {
    const labels: Record<string, string> = {
        full_time: 'Full Time',
        part_time: 'Part Time',
        contract: 'Kontrak',
        internship: 'Magang',
        resigned: 'Keluar',
    };

    return labels[status] ?? status;
}

type CreateColumnsParams = {
    handleEdit: (employee: Employee) => void;
    handleDeleteClick: (employee: Employee) => void;
    handleResetPassword: (employee: Employee) => void;
    toggleActiveUrl: (id: number) => string;
    can: (permission: string) => boolean;
    canViewAll: boolean;
};

export function createEmployeeColumns(
    params: CreateColumnsParams,
): ColumnDef<Employee>[] {
    const {
        handleEdit,
        handleDeleteClick,
        handleResetPassword,
        toggleActiveUrl,
        can,
        canViewAll,
    } = params;

    const columns: ColumnDef<Employee>[] = [
        {
            id: 'photo',
            header: () => <span>Foto</span>,
            meta: { className: 'w-[60px]' },
            cell: ({ row }) => {
                const employee = row.original;
                const fullName = employee.user_profile?.full_name ?? '';
                const initials = fullName
                    .split(' ')
                    .map((n) => n[0])
                    .join('')
                    .toUpperCase()
                    .slice(0, 2);

                return (
                    <Avatar className="h-10 w-10">
                        <AvatarImage
                            src={employee.photo_url ?? undefined}
                            alt={fullName}
                        />
                        <AvatarFallback className="text-xs">
                            {initials || '-'}
                        </AvatarFallback>
                    </Avatar>
                );
            },
        },
        {
            accessorKey: 'user_profile.full_name',
            id: 'full_name',
            header: () => <span>Nama</span>,
            cell: ({ row }) => {
                const employee = row.original;

                return (
                    <div className="flex flex-col">
                        <span className="font-medium">
                            {employee.user_profile?.full_name ?? '-'}
                        </span>
                        <span className="text-xs text-muted-foreground">
                            {employee.email}
                        </span>
                    </div>
                );
            },
        },
        {
            accessorKey: 'username',
            header: () => <span>Username</span>,
            cell: ({ row }) => (
                <span className="font-medium">
                    {row.getValue('username') as string}
                </span>
            ),
        },
        {
            accessorKey: 'user_profile.phone_number',
            id: 'phone_number',
            header: () => <span>No. Telepon</span>,
            cell: ({ row }) => {
                const employee = row.original;

                return (
                    <span>{employee.user_profile?.phone_number ?? '-'}</span>
                );
            },
        },
        {
            accessorKey: 'employee.base_salary',
            id: 'base_salary',
            header: () => <span>Gaji</span>,
            cell: ({ row }) => {
                const employee = row.original;
                const salary = employee.employee?.base_salary;

                if (!salary) {
                    return <span>-</span>;
                }

                return (
                    <span className="font-medium">
                        {formatCurrency(salary)}
                    </span>
                );
            },
        },
        {
            id: 'period',
            header: () => <span>Masa Kerja</span>,
            cell: ({ row }) => {
                const employee = row.original;
                const joinDate = employee.employee?.join_date;
                const resignDate = employee.employee?.resign_date;

                if (!joinDate) {
                    return <span>-</span>;
                }

                const formattedJoin = new Date(joinDate).toLocaleDateString('id-ID', {
                    day: 'numeric',
                    month: 'short',
                    year: 'numeric',
                });

                if (resignDate) {
                    const formattedResign = new Date(resignDate).toLocaleDateString('id-ID', {
                        day: 'numeric',
                        month: 'short',
                        year: 'numeric',
                    });
                    return (
                        <div className="flex flex-col">
                            <span className="text-xs text-muted-foreground">Masuk</span>
                            <span>{formattedJoin}</span>
                            <span className="text-xs text-muted-foreground">Keluar</span>
                            <span>{formattedResign}</span>
                        </div>
                    );
                }

                return (
                    <div className="flex flex-col">
                        <span className="text-xs text-muted-foreground">Masuk</span>
                        <span>{formattedJoin}</span>
                    </div>
                );
            },
        },
        ...(canViewAll
            ? [
                  {
                      id: 'role',
                      header: () => <span>Role</span>,
                      cell: ({ row }) => {
                          const employee = row.original;
                          const roleName =
                              employee.roles?.[0]?.name ?? '-';

                          return (
                              <span className="inline-flex items-center rounded-md bg-muted px-2 py-1 text-xs font-medium">
                                  {roleName}
                              </span>
                          );
                      },
                  },
              ]
            : []),
        {
            accessorKey: 'employee.employment_status',
            id: 'employment_status',
            header: () => <span>Status</span>,
            cell: ({ row }) => {
                const employee = row.original;
                const status = employee.employee?.employment_status;

                if (!status) {
                    return <span>-</span>;
                }

                return (
                    <span className="inline-flex items-center rounded-md bg-muted px-2 py-1 text-xs font-medium">
                        {getEmploymentStatusLabel(status)}
                    </span>
                );
            },
        },
        {
            accessorKey: 'is_active',
            header: () => <span className="block text-center">Aktif</span>,
            meta: {
                className: 'w-[80px] text-center',
                headerClassName: 'w-[80px] text-center',
            },
            cell: ({ row }) => {
                const employee = row.original;

                return (
                    <div className="flex justify-center">
                        <ToggleStatus
                            url={toggleActiveUrl(employee.id)}
                            checked={employee.is_active}
                            wrapperClassName="flex items-center justify-center gap-1"
                            disabled={!can('employees.toggle_status')}
                        />
                    </div>
                );
            },
        },
    ];

    if (
        can('employees.update') ||
        can('employees.reset_password') ||
        can('employees.delete')
    ) {
        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 employee = row.original;

                return (
                    <RowActions
                        actions={[
                            {
                                label: 'Edit',
                                icon: <Pencil className="h-4 w-4" />,
                                show: can('employees.update'),
                                onClick: () => handleEdit(employee),
                            },
                            {
                                label: 'Reset Kata Sandi',
                                icon: (
                                    <KeyRound className="h-4 w-4 text-muted-foreground" />
                                ),
                                show: can('employees.reset_password'),
                                onClick: () => handleResetPassword(employee),
                            },
                            {
                                label: 'Hapus',
                                icon: (
                                    <Trash2 className="h-4 w-4 text-destructive" />
                                ),
                                show: can('employees.delete'),
                                onClick: () => handleDeleteClick(employee),
                            },
                        ]}
                    />
                );
            },
        });
    }

    return columns;
}
