'use client';

import { useMemo } from 'react';
import { parseAsInteger, parseAsString, useQueryStates } from 'nuqs';
import { useSuspenseQuery } from '@tanstack/react-query';
import { DataTable } from '@/components/ui/table/data-table';
import { DataTableToolbar } from '@/components/ui/table/data-table-toolbar';
import { useDataTable } from '@/hooks/use-data-table';
import { getSortingStateParser } from '@/lib/parsers';
import { customersQueryOptions } from '../api/queries';
import type { CustomerReferenceData } from '../api/types';
import { getCustomerColumns } from './customer-columns';

export function CustomersTable({
  referenceData,
  canUpdate,
  canDelete
}: {
  referenceData: CustomerReferenceData;
  canUpdate: boolean;
  canDelete: boolean;
}) {
  const columns = useMemo(
    () => getCustomerColumns({ referenceData, canUpdate, canDelete }),
    [referenceData, canUpdate, canDelete]
  );
  const columnIds = columns.map((column) => column.id).filter(Boolean) as string[];
  const [params] = useQueryStates({
    page: parseAsInteger.withDefault(1),
    perPage: parseAsInteger.withDefault(10),
    name: parseAsString,
    customerStatus: parseAsString,
    customerType: parseAsString,
    branch: parseAsString,
    sort: getSortingStateParser(columnIds).withDefault([])
  });

  const filters = {
    page: params.page,
    limit: params.perPage,
    ...(params.name && { search: params.name }),
    ...(params.customerStatus && { customerStatus: params.customerStatus }),
    ...(params.customerType && { customerType: params.customerType }),
    ...(params.branch && { branch: params.branch }),
    ...(params.sort.length > 0 && { 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,
    shallow: true,
    debounceMs: 500,
    initialState: {
      columnPinning: { right: ['actions'] }
    }
  });

  return (
    <DataTable table={table}>
      <DataTableToolbar table={table} />
    </DataTable>
  );
}
