'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 { QuotationListItem, QuotationReferenceData } from '../api/types';
import { QuotationCellAction } from './quotation-cell-action';
import { QuotationStatusBadge } from './quotation-status-badge';

export function getQuotationColumns({
  referenceData,
  canUpdate,
  canDelete
}: {
  referenceData: QuotationReferenceData;
  canUpdate: boolean;
  canDelete: boolean;
}): ColumnDef<QuotationListItem>[] {
  const statusMap = new Map(referenceData.statuses.map((item) => [item.id, item]));
  const typeMap = new Map(referenceData.quotationTypes.map((item) => [item.id, item]));
  const branchMap = new Map(referenceData.branches.map((item) => [item.id, item]));

  return [
    {
      id: 'code',
      accessorKey: 'code',
      header: ({ column }: { column: Column<QuotationListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='ใบเสนอราคา' />
      ),
      cell: ({ row }) => (
        <div className='flex flex-col'>
          <Link href={`/dashboard/crm/quotations/${row.original.id}`} className='font-medium hover:underline'>
            {row.original.code}
          </Link>
          <span className='text-muted-foreground text-xs'>
            {row.original.customerName}
            {row.original.projectName ? ` - ${row.original.projectName}` : ''}
          </span>
        </div>
      ),
      meta: {
        label: 'ใบเสนอราคา',
        placeholder: 'ค้นหาใบเสนอราคา...',
        variant: 'text' as const,
        icon: Icons.search
      },
      enableColumnFilter: true
    },
    {
      id: 'status',
      accessorKey: 'status',
      header: ({ column }: { column: Column<QuotationListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='Status' />
      ),
      cell: ({ row }) => {
        const status = statusMap.get(row.original.status);
        return <QuotationStatusBadge 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: 'quotationType',
      accessorKey: 'quotationType',
      header: ({ column }: { column: Column<QuotationListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='ประเภท' />
      ),
      cell: ({ row }) => (
        <Badge variant='outline'>
          {typeMap.get(row.original.quotationType)?.label ?? 'Unknown'}
        </Badge>
      ),
      meta: {
        label: 'ประเภท',
        variant: 'multiSelect' as const,
        options: referenceData.quotationTypes.map((item) => ({ value: item.id, label: item.label }))
      },
      enableColumnFilter: true
    },
    {
      id: 'branch',
      accessorFn: (row) => row.branchId ?? '',
      header: ({ column }: { column: Column<QuotationListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='สาขา' />
      ),
      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: 'customer',
      accessorFn: (row) => row.customerId,
      header: ({ column }: { column: Column<QuotationListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='ลูกค้าผู้รับใบเสนอราคา' />
      ),
      cell: ({ row }) => row.original.customerName,
      meta: {
        label: 'ลูกค้าผู้รับใบเสนอราคา',
        variant: 'multiSelect' as const,
        options: referenceData.customers.map((item) => ({ value: item.id, label: item.name }))
      },
      enableColumnFilter: true
    },
    {
      id: 'enquiry',
      accessorFn: (row) => row.enquiryId ?? '',
      header: ({ column }: { column: Column<QuotationListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='โอกาสขาย' />
      ),
      cell: ({ row }) => row.original.enquiryCode ?? '-',
      meta: {
        label: 'โอกาสขาย',
        variant: 'multiSelect' as const,
        options: referenceData.enquiries.map((item) => ({ value: item.id, label: `${item.code} - ${item.title}` }))
      },
      enableColumnFilter: true
    },
    {
      id: 'isHotProject',
      accessorFn: (row) => String(row.isHotProject),
      header: ({ column }: { column: Column<QuotationListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='ด่วน' />
      ),
      cell: ({ row }) => (row.original.isHotProject ? <Badge>Hot</Badge> : <span>-</span>),
      meta: {
        label: 'โครงการด่วน',
        variant: 'multiSelect' as const,
        options: [
          { value: 'true', label: 'ด่วน' },
          { value: 'false', label: 'ปกติ' }
        ]
      },
      enableColumnFilter: true
    },
    {
      id: 'totalAmount',
      accessorKey: 'totalAmount',
      header: ({ column }: { column: Column<QuotationListItem, unknown> }) => (
        <DataTableColumnHeader column={column} title='มูลค่ารวม' />
      ),
      cell: ({ row }) => row.original.totalAmount.toLocaleString()
    },
    {
      id: 'actions',
      cell: ({ row }) => (
        <QuotationCellAction
          data={row.original}
          referenceData={referenceData}
          canUpdate={canUpdate}
          canDelete={canDelete}
        />
      )
    }
  ];
}
