// src/features/surveys/hooks/useTableConfig.ts
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
import type { TableConfigDto } from '../types/survey.types';

const BASE = import.meta.env.VITE_API_URL;

const getHeaders = () => ({
  Authorization: `Bearer ${localStorage.getItem('zelisy_access_token')}`,
  'X-Organization-Id': localStorage.getItem('zelisy_org_id') ?? '',
});

/**
 * Custom hook for table config.
 *
 * @param tableName - The table name.
 * @returns The hook's state and actions.
 */
export function useTableConfig<T = any>(tableName: string) {
  const { data, isLoading, isError } = useQuery({
    queryKey: ['table-config', tableName],
    queryFn: async () => {
      const res = await axios.get<TableConfigDto>(
        `${BASE}/tables/${tableName}/config`,
        { headers: getHeaders() }
      );
      return res.data; // ← critical: unwrap AxiosResponse
    },
    staleTime: 5 * 60_000,
    gcTime: 10 * 60_000,
    retry: 2,
  });

  const columns = (data?.columns ?? []).map((col) => ({
    key: col.key as keyof T & string,
    label: col.label,
    cellType: col.cellType ?? undefined,
    align: col.align ?? 'left',
    width: col.width ?? undefined,
    minWidth: col.minWidth ?? undefined,
    maxWidth: col.maxWidth ?? undefined,
    sortable: col.sortable,
    hidden: col.hidden ?? false,
    hideBelow: col.hideBelow ?? undefined,
    className: col.className ?? undefined,
    toggleable: col.toggleable ?? true,
  }));

  const tabs = (data?.tabs ?? []).map((t) => ({
    key: t.key,
    label: t.label,
    count: t.count,
    icon: t.icon,
  }));

  const controls = (data?.controls ?? []).map((c) => ({
    action: c.action,
    label: c.label,
    icon: c.icon,
    variant: c.variant,
    showOnSelection: c.showOnSelection ?? false,
    disabled: c.disabled ?? false,
    onClick: undefined as (() => void) | undefined,
  }));

  return {
    columns,
    tabs,
    controls,
    defaultSortBy: data?.defaultSortBy ?? 'createdAt',
    defaultSortOrder: (data?.defaultSortOrder ?? 'desc') as 'asc' | 'desc',
    defaultPageSize: data?.defaultPageSize ?? 50,
    tabFilterKey: data?.tabFilterKey ?? undefined,
    isLoading,
    isError,
  };
}
