'use client';

import { useMemo, useState } from 'react';
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 { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Icons } from '@/components/icons';
import { customersQueryOptions, crmReferenceQueryOptions } from '../api/queries';
import type { Customer } from '../api/types';
import { CustomerFormSheet } from './customer-form-sheet';
import { BranchBadge, CustomerStatusBadge } from './shared';

export function CustomersTablePage() {
  const [editingCustomer, setEditingCustomer] = useState<Customer | undefined>();
  const [sheetOpen, setSheetOpen] = useState(false);

  const columns = useMemo<ColumnDef<Customer>[]>(
    () => [
      {
        accessorKey: 'code',
        header: 'Code',
        cell: ({ row }) => <span className='font-medium'>{row.original.code}</span>
      },
      {
        accessorKey: 'name',
        header: 'Customer',
        cell: ({ row }) => (
          <div>
            <p className='font-medium'>{row.original.name}</p>
            <p className='text-muted-foreground text-sm'>{row.original.email}</p>
          </div>
        )
      },
      {
        accessorKey: 'customerStatus',
        header: 'Status',
        cell: ({ row }) => <CustomerStatusBadge status={row.original.customerStatus} />
      },
      {
        accessorKey: 'branchId',
        header: 'Branch',
        cell: ({ row, table }) => {
          const branches = (
            table.options.meta as {
              branches: Array<{
                id: string;
                code: string;
                name: string;
                region: string;
              }>;
            }
          ).branches;
          const branch = branches.find((item) => item.id === row.original.branchId);
          return branch ? <BranchBadge branch={branch} /> : null;
        }
      },
      {
        accessorKey: 'contactIds',
        header: 'Contacts',
        cell: ({ row }) => row.original.contactIds.length
      },
      {
        id: 'actions',
        header: '',
        cell: ({ row }) => (
          <div className='flex justify-end gap-2'>
            <Button
              variant='outline'
              size='sm'
              onClick={() => {
                setEditingCustomer(row.original);
                setSheetOpen(true);
              }}
            >
              Edit
            </Button>
            <Button variant='outline' size='sm' asChild>
              <Link href={`/dashboard/crm-demo/customers/${row.original.id}`}>View</Link>
            </Button>
          </div>
        )
      }
    ],
    []
  );

  const columnIds = ['code', 'name', 'customerStatus', 'branchId', 'contactIds', 'actions'];

  const [params, setParams] = useQueryStates({
    page: parseAsInteger.withDefault(1),
    perPage: parseAsInteger.withDefault(10),
    name: parseAsString,
    customerStatus: parseAsString,
    branch: parseAsString,
    sort: getSortingStateParser(columnIds).withDefault([])
  });
  const { data: reference } = useSuspenseQuery(crmReferenceQueryOptions());

  const filters = {
    page: params.page,
    limit: params.perPage,
    ...(params.name && { search: params.name }),
    ...(params.customerStatus && { status: params.customerStatus }),
    ...(params.branch && { branch: params.branch }),
    ...(params.sort.length ? { sort: JSON.stringify(params.sort) } : {})
  };

  const { data } = useSuspenseQuery(customersQueryOptions(filters));
  const pageCount = Math.ceil(data.totalItems / params.perPage);

  const { table } = useDataTable({
    data: data.items,
    columns,
    pageCount,
    meta: { branches: reference.branches },
    initialState: {
      columnPinning: { right: ['actions'] }
    }
  });

  return (
    <div className='flex flex-1 flex-col space-y-4'>
      <div className='flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between'>
        <div className='grid gap-3 md:grid-cols-3 lg:w-full'>
          <Input
            placeholder='ค้นหา customer หรือ code'
            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.customerStatus ?? ''}
            onChange={(event) =>
              void setParams({
                customerStatus: event.target.value || null,
                page: 1
              })
            }
          >
            <option value=''>ทุกสถานะ</option>
            <option value='active'>Active</option>
            <option value='prospect'>Prospect</option>
            <option value='inactive'>Inactive</option>
          </select>
          <select
            className='border-input bg-background rounded-md border px-3 text-sm'
            value={params.branch ?? ''}
            onChange={(event) => void setParams({ branch: event.target.value || null, page: 1 })}
          >
            <option value=''>ทุกสาขา</option>
            {reference.branches.map((branch) => (
              <option key={branch.id} value={branch.id}>
                {branch.name}
              </option>
            ))}
          </select>
        </div>
        <Button
          onClick={() => {
            setEditingCustomer(undefined);
            setSheetOpen(true);
          }}
        >
          <Icons.add className='mr-2 h-4 w-4' />
          Create Customer
        </Button>
      </div>

      <DataTable table={table} />
      <CustomerFormSheet
        open={sheetOpen}
        onOpenChange={(open) => {
          setSheetOpen(open);
          if (!open) setEditingCustomer(undefined);
        }}
        customer={editingCustomer}
      />
    </div>
  );
}
