import { columns, statusKey, WorkerColumn } from './components/worker-columns';
import { DocsButton } from '@/components/v1/docs/docs-button';
import { ToolbarType } from '@/components/v1/molecules/data-table/data-table-toolbar';
import { DataTable } from '@/components/v1/molecules/data-table/data-table.tsx';
import { Loading } from '@/components/v1/ui/loading.tsx';
import { useRefetchInterval } from '@/contexts/refetch-interval-context';
import { useLocalStorageState } from '@/hooks/use-local-storage-state';
import { usePagination } from '@/hooks/use-pagination';
import { useCurrentTenantId } from '@/hooks/use-tenant';
import { useZodColumnFilters } from '@/hooks/use-zod-column-filters';
import { queries } from '@/lib/api';
import { WorkerStatus } from '@/lib/api/generated/data-contracts';
import { docsPages } from '@/lib/generated/docs';
import { useQuery } from '@tanstack/react-query';
import { VisibilityState } from '@tanstack/react-table';
import { useMemo, useState, useCallback } from 'react';
import { z } from 'zod';

const workersQuerySchema = z
  .object({
    s: z.array(z.enum(['ACTIVE', 'INACTIVE', 'PAUSED'])).optional(), // status
  })
  .default({})
  .transform((data) => ({
    s: data.s ?? ['ACTIVE', 'PAUSED'],
  }));

export default function Workers() {
  const { tenantId } = useCurrentTenantId();
  const { refetchInterval } = useRefetchInterval();
  const paramKey = 'workers-table';
  const { pagination, setPagination, limit, offset, setPageSize } =
    usePagination({
      key: paramKey,
    });
  const [openLabelsPopover, setOpenLabelsPopover] = useState<string | null>(
    null,
  );

  const {
    state: { s: statuses },
    columnFilters,
    setColumnFilters,
    resetFilters,
  } = useZodColumnFilters(workersQuerySchema, paramKey, { s: statusKey });

  const [columnVisibility, setColumnVisibility] =
    useLocalStorageState<VisibilityState>('hatchet:columns:workers', {});

  const handleSetOpenLabelsPopover = useCallback(
    (id: string | null) => setOpenLabelsPopover(id),
    [],
  );

  const tableColumns = useMemo(
    () => columns(tenantId, openLabelsPopover, handleSetOpenLabelsPopover),
    [tenantId, openLabelsPopover, handleSetOpenLabelsPopover],
  );

  const listWorkersQuery = useQuery({
    ...queries.workers.list(tenantId, {
      offset,
      limit,
      statuses: statuses as WorkerStatus[],
    }),
    refetchInterval,
  });

  const rows = listWorkersQuery.data?.rows ?? [];
  const pageCount =
    listWorkersQuery.data?.pagination?.num_pages ??
    Math.ceil(rows.length / limit);

  if (listWorkersQuery.isLoading) {
    return <Loading />;
  }

  return (
    <DataTable
      columns={tableColumns}
      data={rows}
      filters={[
        {
          columnId: 'status',
          title: 'Status',
          type: ToolbarType.Checkbox,
          options: [
            { value: 'ACTIVE', label: 'Active' },
            { value: 'PAUSED', label: 'Paused' },
            { value: 'INACTIVE', label: 'Inactive' },
          ],
        },
      ]}
      emptyState={
        <div className="flex h-full w-full flex-col items-center justify-center gap-y-4 py-8 text-foreground">
          <p className="text-lg font-semibold">No workers found</p>
          <div className="w-fit">
            <DocsButton
              doc={docsPages.v1.workers}
              label="Learn about running workers"
            />
          </div>
        </div>
      }
      columnFilters={columnFilters}
      setColumnFilters={setColumnFilters}
      columnVisibility={columnVisibility}
      setColumnVisibility={setColumnVisibility}
      showColumnToggle={true}
      columnKeyToName={WorkerColumn}
      refetchProps={{
        isRefetching: listWorkersQuery.isRefetching,
        onRefetch: listWorkersQuery.refetch,
      }}
      onResetFilters={resetFilters}
      pagination={pagination}
      setPagination={setPagination}
      onSetPageSize={setPageSize}
      pageCount={pageCount}
    />
  );
}
