'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 { EnquiryListItem, EnquiryReferenceData } from '../api/types';
import { EnquiryCellAction } from './enquiry-cell-action';
import { EnquiryStatusBadge } from './enquiry-status-badge';

function getLeadColumns({
  referenceData,
  canUpdate,
  canDelete,
  canAssign,
  canReassign
}: SharedColumnsConfig): ColumnDef<EnquiryListItem>[] {
  const statusMap = new Map(referenceData.statuses.map((item) => [item.id, item]));
  const leadChannelMap = new Map(referenceData.leadChannels.map((item) => [item.id, item.label]));

  return [
    {
      id: 'code',
      accessorKey: 'code',
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Code' />
      ),
      cell: ({ row }) => (
        <div className='flex flex-col'>
          <Link
            href={`/dashboard/crm/leads/${row.original.id}`}
            className='font-medium hover:underline'
          >
            {row.original.code}
          </Link>
          <span className='text-muted-foreground text-xs'>{row.original.title}</span>
        </div>
      ),
      meta: {
        label: 'Code',
        placeholder: 'Search leads...',
        variant: 'text' as const,
        icon: Icons.search
      },
      enableColumnFilter: true
    },
    {
      id: 'leadChannel',
      accessorFn: (row) => row.leadChannel ?? '',
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Lead Source' />
      ),
      cell: ({ row }) => <span>{leadChannelMap.get(row.original.leadChannel ?? '') ?? '-'}</span>
    },
    {
      id: 'customer',
      accessorFn: (row) => row.customerId,
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Company' />
      ),
      cell: ({ row }) => <span>{row.original.customerName}</span>,
      meta: {
        label: 'Company',
        variant: 'multiSelect' as const,
        options: referenceData.customers.map((item) => ({
          value: item.id,
          label: item.name
        }))
      },
      enableColumnFilter: true
    },
    {
      id: 'contact',
      accessorFn: (row) => row.contactId ?? '',
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Contact' />
      ),
      cell: ({ row }) => <span>{row.original.contactName ?? '-'}</span>
    },
    {
      id: 'assignedSales',
      accessorFn: (row) => row.assignedToName ?? '',
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Assigned Sales' />
      ),
      cell: ({ row }) => <span>{row.original.assignedToName ?? 'Unassigned'}</span>
    },
    {
      id: 'createdBy',
      accessorFn: (row) => row.createdByName ?? row.createdBy,
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Created By' />
      ),
      cell: ({ row }) => <span>{row.original.createdByName ?? row.original.createdBy}</span>
    },
    {
      id: 'createdAt',
      accessorKey: 'createdAt',
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Created At' />
      ),
      cell: ({ row }) => <span>{new Date(row.original.createdAt).toLocaleDateString()}</span>
    },
    {
      id: 'age',
      accessorFn: (row) => row.createdAt,
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Age' />
      ),
      cell: ({ row }) => {
        const ageInDays = Math.max(
          0,
          Math.floor(
            (Date.now() - new Date(row.original.createdAt).getTime()) / (1000 * 60 * 60 * 24)
          )
        );

        return <span>{ageInDays} days</span>;
      }
    },
    {
      id: 'status',
      accessorKey: 'status',
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Status' />
      ),
      cell: ({ row }) => {
        const status = statusMap.get(row.original.status);
        return <EnquiryStatusBadge code={status?.code} label={status?.label ?? 'Unknown'} />;
      },
      meta: {
        label: 'Status',
        variant: 'multiSelect' as const,
        options: referenceData.statuses.map((item) => ({
          value: item.id,
          label: item.label
        }))
      },
      enableColumnFilter: true
    },
    {
      id: 'actions',
      cell: ({ row }) => (
        <EnquiryCellAction
          data={row.original}
          referenceData={referenceData}
          workspace='lead'
          canUpdate={canUpdate}
          canDelete={canDelete}
          canAssign={canAssign}
          canReassign={canReassign}
        />
      )
    }
  ];
}

function getEnquiryWorkspaceColumns({
  referenceData,
  canUpdate,
  canDelete,
  canAssign,
  canReassign
}: SharedColumnsConfig): ColumnDef<EnquiryListItem>[] {
  const statusMap = new Map(referenceData.statuses.map((item) => [item.id, item]));

  return [
    {
      id: 'code',
      accessorKey: 'code',
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Code' />
      ),
      cell: ({ row }) => (
        <div className='flex flex-col'>
          <Link
            href={`/dashboard/crm/enquiries/${row.original.id}`}
            className='font-medium hover:underline'
          >
            {row.original.code}
          </Link>
          <span className='text-muted-foreground text-xs'>{row.original.title}</span>
        </div>
      ),
      meta: {
        label: 'Code',
        placeholder: 'Search enquiries...',
        variant: 'text' as const,
        icon: Icons.search
      },
      enableColumnFilter: true
    },
    {
      id: 'projectName',
      accessorFn: (row) => row.projectName ?? row.title,
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Project' />
      ),
      cell: ({ row }) => <span>{row.original.projectName ?? row.original.title}</span>
    },
    {
      id: 'customer',
      accessorFn: (row) => row.customerId,
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='ลูกค้าผู้รับใบเสนอราคา' />
      ),
      cell: ({ row }) => <span>{row.original.customerName}</span>,
      meta: {
        label: 'ลูกค้าผู้รับใบเสนอราคา',
        variant: 'multiSelect' as const,
        options: referenceData.customers.map((item) => ({
          value: item.id,
          label: item.name
        }))
      },
      enableColumnFilter: true
    },
    {
      id: 'assignedSales',
      accessorFn: (row) => row.assignedToName ?? '',
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Enquiry Owner' />
      ),
      cell: ({ row }) => <span>{row.original.assignedToName ?? '-'}</span>
    },
    {
      id: 'chancePercent',
      accessorKey: 'chancePercent',
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Chance %' />
      ),
      cell: ({ row }) => (
        <span>{row.original.chancePercent !== null ? `${row.original.chancePercent}%` : '-'}</span>
      )
    },
    {
      id: 'estimatedValue',
      accessorKey: 'estimatedValue',
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Estimated Value' />
      ),
      cell: ({ row }) => (
        <span>
          {row.original.estimatedValue !== null
            ? row.original.estimatedValue.toLocaleString()
            : '-'}
        </span>
      )
    },
    {
      id: 'quotationCount',
      accessorKey: 'quotationCount',
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Quotation Count' />
      ),
      cell: ({ row }) => <span>{row.original.quotationCount}</span>
    },
    {
      id: 'nextFollowupDate',
      accessorKey: 'nextFollowupDate',
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Next Follow-up' />
      ),
      cell: ({ row }) => (
        <span>
          {row.original.nextFollowupDate
            ? new Date(row.original.nextFollowupDate).toLocaleDateString()
            : '-'}
        </span>
      )
    },
    {
      id: 'status',
      accessorKey: 'status',
      header: ({ column }: { column: Column<EnquiryListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Status' />
      ),
      cell: ({ row }) => {
        const status = statusMap.get(row.original.status);
        return <EnquiryStatusBadge code={status?.code} label={status?.label ?? 'Unknown'} />;
      },
      meta: {
        label: 'Status',
        variant: 'multiSelect' as const,
        options: referenceData.statuses.map((item) => ({
          value: item.id,
          label: item.label
        }))
      },
      enableColumnFilter: true
    },
    {
      id: 'actions',
      cell: ({ row }) => (
        <EnquiryCellAction
          data={row.original}
          referenceData={referenceData}
          workspace='enquiry'
          canUpdate={canUpdate}
          canDelete={canDelete}
          canAssign={canAssign}
          canReassign={canReassign}
        />
      )
    }
  ];
}

type SharedColumnsConfig = {
  referenceData: EnquiryReferenceData;
  canUpdate: boolean;
  canDelete: boolean;
  canAssign: boolean;
  canReassign: boolean;
};

export function getEnquiryColumns({
  referenceData,
  workspace,
  canUpdate,
  canDelete,
  canAssign,
  canReassign
}: SharedColumnsConfig & {
  workspace: 'lead' | 'enquiry';
}): ColumnDef<EnquiryListItem>[] {
  const sharedConfig = {
    referenceData,
    canUpdate,
    canDelete,
    canAssign,
    canReassign
  };

  return workspace === 'lead'
    ? getLeadColumns(sharedConfig)
    : getEnquiryWorkspaceColumns(sharedConfig);
}
