'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 { opportunitiesQueryOptions } from '../api/queries';
import type { OpportunityReferenceData } from '../api/types';
import { getOpportunityColumns } from './opportunity-columns';

export function OpportunitiesTable({
  referenceData,
  workspace,
  canUpdate,
  canDelete,
  canAssign,
  canReassign
}: {
  referenceData: OpportunityReferenceData;
  workspace: 'lead' | 'opportunity';
  canUpdate: boolean;
  canDelete: boolean;
  canAssign: boolean;
  canReassign: boolean;
}) {
  const columns = useMemo(
    () =>
      getOpportunityColumns({
        referenceData,
        workspace,
        canUpdate,
        canDelete,
        canAssign,
        canReassign
      }),
    [referenceData, workspace, canUpdate, canDelete, canAssign, canReassign]
  );

  const columnIds = columns.map((column) => column.id).filter(Boolean) as string[];
  const [params] = useQueryStates({
    page: parseAsInteger.withDefault(1),
    perPage: parseAsInteger.withDefault(10),
    name: parseAsString,
    status: parseAsString,
    productType: parseAsString,
    priority: parseAsString,
    branch: parseAsString,
    customer: parseAsString,
    sort: getSortingStateParser(columnIds).withDefault([])
  });

  const filters = {
    page: params.page,
    limit: params.perPage,
    pipelineStage: workspace,
    ...(params.name && { search: params.name }),
    ...(params.status && { status: params.status }),
    ...(params.productType && { productType: params.productType }),
    ...(params.priority && { priority: params.priority }),
    ...(params.branch && { branch: params.branch }),
    ...(params.customer && { customer: params.customer }),
    ...(params.sort.length > 0 && { sort: JSON.stringify(params.sort) })
  };

  const { data } = useSuspenseQuery(opportunitiesQueryOptions(filters));
  const pageCount = Math.max(1, Math.ceil((data.totalItems || 0) / params.perPage));

  const { table } = useDataTable({
    data: data.items,
    columns,
    pageCount,
    shallow: true,
    debounceMs: 500,
    clearOnDefault: true
  });

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

