'use client';

import Link from 'next/link';
import type { Column, ColumnDef } from '@tanstack/react-table';
import { Badge } from '@/components/ui/badge';
import { DataTableColumnHeader } from '@/components/ui/table/data-table-column-header';
import { Icons } from '@/components/icons';
import type { CustomerListItem, CustomerReferenceData } from '../api/types';
import { CustomerCellAction } from './customer-cell-action';
import { CustomerStatusBadge } from './customer-status-badge';

export function getCustomerColumns({
  referenceData,
  canUpdate,
  canDelete
}: {
  referenceData: CustomerReferenceData;
  canUpdate: boolean;
  canDelete: boolean;
}): ColumnDef<CustomerListItem>[] {
  const branchMap = new Map(referenceData.branches.map((item) => [item.id, item]));
  const typeMap = new Map(referenceData.customerTypes.map((item) => [item.id, item]));
  const statusMap = new Map(referenceData.customerStatuses.map((item) => [item.id, item]));
  const groupMap = new Map(referenceData.customerGroups.map((item) => [item.id, item.label]));
  const subGroupMap = new Map(referenceData.customerSubGroups.map((item) => [item.id, item.label]));

  return [
    {
      id: 'name',
      accessorKey: 'name',
      header: ({ column }: { column: Column<CustomerListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='ลูกค้า' />
      ),
      cell: ({ row }) => (
        <div className='flex flex-col'>
          <Link
            href={`/dashboard/crm/customers/${row.original.id}`}
            className='font-medium hover:underline'
          >
            {row.original.name}
          </Link>
          <span className='text-muted-foreground text-xs'>
            {row.original.code}
            {row.original.email ? ` • ${row.original.email}` : ''}
          </span>
        </div>
      ),
      meta: {
        label: 'ลูกค้า',
        placeholder: 'ค้นหาลูกค้า...',
        variant: 'text' as const,
        icon: Icons.search
      },
      enableColumnFilter: true
    },
    {
      id: 'customerStatus',
      accessorKey: 'customerStatus',
      header: ({ column }: { column: Column<CustomerListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Status' />
      ),
      cell: ({ row }) => {
        const option = statusMap.get(row.original.customerStatus);
        return <CustomerStatusBadge code={option?.code} label={option?.label ?? 'Unknown'} />;
      },
      meta: {
        label: 'Status',
        variant: 'multiSelect' as const,
        options: referenceData.customerStatuses.map((item) => ({
          value: item.id,
          label: item.label
        }))
      },
      enableColumnFilter: true
    },
    {
      id: 'customerType',
      accessorKey: 'customerType',
      header: ({ column }: { column: Column<CustomerListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Type' />
      ),
      cell: ({ row }) => (
        <Badge variant='outline'>
          {typeMap.get(row.original.customerType)?.label ?? 'Unknown'}
        </Badge>
      ),
      meta: {
        label: 'ประเภท',
        variant: 'multiSelect' as const,
        options: referenceData.customerTypes.map((item) => ({
          value: item.id,
          label: item.label
        }))
      },
      enableColumnFilter: true
    },
    {
      id: 'branch',
      accessorFn: (row) => row.branchId ?? '',
      header: ({ column }: { column: Column<CustomerListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Branch' />
      ),
      cell: ({ row }) => (
        <span>
          {row.original.branchId
            ? (branchMap.get(row.original.branchId)?.name ?? 'Unknown')
            : 'Unassigned'}
        </span>
      ),
      meta: {
        label: 'สาขา',
        variant: 'multiSelect' as const,
        options: referenceData.branches.map((item) => ({
          value: item.id,
          label: item.name
        }))
      },
      enableColumnFilter: true
    },
    {
      id: 'customerGroup',
      accessorKey: 'customerGroup',
      header: ({ column }: { column: Column<CustomerListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Group' />
      ),
      cell: ({ row }) => <span>{groupMap.get(row.original.customerGroup ?? '') ?? '-'}</span>
    },
    {
      id: 'customerSubGroup',
      accessorKey: 'customerSubGroup',
      header: ({ column }: { column: Column<CustomerListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Sub Group' />
      ),
      cell: ({ row }) => <span>{subGroupMap.get(row.original.customerSubGroup ?? '') ?? '-'}</span>
    },
    {
      id: 'contactCount',
      accessorKey: 'contactCount',
      header: ({ column }: { column: Column<CustomerListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='ผู้ติดต่อ' />
      ),
      cell: ({ row }) => <span>{row.original.contactCount}</span>
    },
    {
      id: 'actions',
      cell: ({ row }) => (
        <CustomerCellAction
          data={row.original}
          referenceData={referenceData}
          canUpdate={canUpdate}
          canDelete={canDelete}
        />
      )
    }
  ];
}
