'use client';

import Link from 'next/link';
import { useSuspenseQuery } from '@tanstack/react-query';
import { type ColumnDef } from '@tanstack/react-table';
import { parseAsInteger, parseAsString, useQueryStates } from 'nuqs';
import { getSortingStateParser } from '@/lib/parsers';
import { useDataTable } from '@/hooks/use-data-table';
import { DataTable } from '@/components/ui/table/data-table';
import { Button } from '@/components/ui/button';
import { Card } from '@/components/ui/card';
import { Input } from '@/components/ui/input';
import { HotProjectPill, QuotationStatusBadge } from './shared';
import { crmReferenceQueryOptions, quotationsQueryOptions } from '../api/queries';
import type { Quotation } from '../api/types';
import { formatCurrency } from '../utils/format';

const columns: ColumnDef<Quotation>[] = [
  { accessorKey: 'code', header: 'Code' },
  { accessorKey: 'project', header: 'Project' },
  { accessorKey: 'quotationType', header: 'Type' },
  {
    accessorKey: 'status',
    header: 'Status',
    cell: ({ row }) => <QuotationStatusBadge status={row.original.status} />
  },
  { accessorKey: 'revision', header: 'Rev' },
  {
    accessorKey: 'totalAmount',
    header: 'Amount',
    cell: ({ row }) => formatCurrency(row.original.totalAmount)
  },
  {
    accessorKey: 'isHotProject',
    header: 'Hot',
    cell: ({ row }) => <HotProjectPill active={row.original.isHotProject} />
  },
  {
    id: 'actions',
    header: '',
    cell: ({ row }) => (
      <div className='flex justify-end gap-2'>
        <Button variant='outline' size='sm' asChild>
          <Link href={`/dashboard/crm-demo/quotations/${row.original.id}`}>View</Link>
        </Button>
      </div>
    )
  }
];

const columnIds = [
  'code',
  'project',
  'quotationType',
  'status',
  'revision',
  'totalAmount',
  'isHotProject',
  'actions'
];

function KanbanView({ items }: { items: Quotation[] }) {
  const statuses = ['draft', 'pending_approval', 'approved', 'sent', 'accepted', 'lost'];

  return (
    <div className='grid gap-4 xl:grid-cols-6'>
      {statuses.map((status) => (
        <Card key={status} className='space-y-3 p-3'>
          <div className='flex items-center justify-between'>
            <p className='text-sm font-semibold capitalize'>{status.replace('_', ' ')}</p>
            <span className='text-muted-foreground text-xs'>
              {items.filter((item) => item.status === status).length}
            </span>
          </div>
          {items
            .filter((item) => item.status === status)
            .map((item) => (
              <Link
                key={item.id}
                href={`/dashboard/crm-demo/quotations/${item.id}`}
                className='block rounded-lg border p-3 text-sm transition-colors hover:bg-muted/40'
              >
                <p className='font-medium'>{item.code}</p>
                <p className='text-muted-foreground mt-1 line-clamp-2'>{item.project}</p>
                <p className='mt-2 font-semibold'>{formatCurrency(item.totalAmount)}</p>
              </Link>
            ))}
        </Card>
      ))}
    </div>
  );
}

export function QuotationsTablePage() {
  const [params, setParams] = useQueryStates({
    page: parseAsInteger.withDefault(1),
    perPage: parseAsInteger.withDefault(10),
    name: parseAsString,
    status: parseAsString,
    quotationType: parseAsString,
    salesman: parseAsString,
    hot: parseAsString,
    dateFrom: parseAsString,
    dateTo: parseAsString,
    view: parseAsString.withDefault('table'),
    sort: getSortingStateParser(columnIds).withDefault([])
  });
  const { data: reference } = useSuspenseQuery(crmReferenceQueryOptions());

  const filters = {
    page: params.page,
    limit: params.perPage,
    ...(params.name && { search: params.name }),
    ...(params.status && { status: params.status }),
    ...(params.quotationType && { quotationType: params.quotationType }),
    ...(params.salesman && { salesman: params.salesman }),
    ...(params.hot && { hot: params.hot }),
    ...(params.dateFrom && { dateFrom: params.dateFrom }),
    ...(params.dateTo && { dateTo: params.dateTo }),
    ...(params.sort.length ? { sort: JSON.stringify(params.sort) } : {})
  };

  const { data } = useSuspenseQuery(quotationsQueryOptions(filters));
  const pageCount = Math.ceil(data.totalItems / params.perPage);
  const { table } = useDataTable({
    data: data.items,
    columns,
    pageCount,
    initialState: {
      columnPinning: { right: ['actions'] }
    }
  });

  return (
    <div className='flex flex-1 flex-col space-y-4'>
      <div className='flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between'>
        <div className='grid gap-3 md:grid-cols-2 xl:grid-cols-7 xl:w-full'>
          <Input
            placeholder='ค้นหา code หรือ project'
            value={params.name ?? ''}
            onChange={(event) => void setParams({ name: event.target.value || null, page: 1 })}
          />
          <select
            className='border-input bg-background rounded-md border px-3 text-sm'
            value={params.status ?? ''}
            onChange={(event) => void setParams({ status: event.target.value || null, page: 1 })}
          >
            <option value=''>ทุกสถานะ</option>
            <option value='draft'>Draft</option>
            <option value='pending_approval'>Pending Approval</option>
            <option value='approved'>Approved</option>
            <option value='sent'>Sent</option>
            <option value='accepted'>Accepted</option>
          </select>
          <select
            className='border-input bg-background rounded-md border px-3 text-sm'
            value={params.quotationType ?? ''}
            onChange={(event) =>
              void setParams({
                quotationType: event.target.value || null,
                page: 1
              })
            }
          >
            <option value=''>ทุกประเภท</option>
            <option value='official'>Official</option>
            <option value='budgetary'>Budgetary</option>
            <option value='service'>Service</option>
          </select>
          <select
            className='border-input bg-background rounded-md border px-3 text-sm'
            value={params.salesman ?? ''}
            onChange={(event) => void setParams({ salesman: event.target.value || null, page: 1 })}
          >
            <option value=''>ทุก salesperson</option>
            {reference.salespersons.map((sales) => (
              <option key={sales.id} value={sales.id}>
                {sales.name}
              </option>
            ))}
          </select>
          <select
            className='border-input bg-background rounded-md border px-3 text-sm'
            value={params.hot ?? ''}
            onChange={(event) => void setParams({ hot: event.target.value || null, page: 1 })}
          >
            <option value=''>ทุกดีล</option>
            <option value='yes'>Hot only</option>
            <option value='no'>Non-hot</option>
          </select>
          <Input
            type='date'
            value={params.dateFrom ?? ''}
            onChange={(event) => void setParams({ dateFrom: event.target.value || null, page: 1 })}
          />
          <Input
            type='date'
            value={params.dateTo ?? ''}
            onChange={(event) => void setParams({ dateTo: event.target.value || null, page: 1 })}
          />
        </div>

        <div className='flex items-center gap-2'>
          <Button variant='outline' asChild>
            <Link href='/dashboard/crm-demo/enquiries'>Create quotation</Link>
          </Button>
          <Button
            variant={params.view === 'table' ? 'default' : 'outline'}
            onClick={() => void setParams({ view: 'table' })}
          >
            Table
          </Button>
          <Button
            variant={params.view === 'kanban' ? 'default' : 'outline'}
            onClick={() => void setParams({ view: 'kanban' })}
          >
            Kanban
          </Button>
        </div>
      </div>

      {params.view === 'kanban' ? <KanbanView items={data.items} /> : <DataTable table={table} />}
    </div>
  );
}
