/**
 * use{{ model_name }}TableState Hook
 *
 * A typed table state hook for {{ model_name }} that composes:
 * - Pagination (from usePagination)
 * - Selection (from useSelection)
 * - Sorting (from useSorting)
 * - Search (from useSearch)
 * - Data fetching (from use{{ model_name }}List)
 *
 * @example
 * ```tsx
 * const table = use{{ model_name }}TableState({
 *   initialPageSize: 20,
 *   enableSelection: true,
 *   initialSort: { field: 'name', direction: 'asc' },
 * });
 *
 * return (
 *   <div>
 *     <SearchInput
 *       value={table.search.query}
 *       onChange={table.search.setQuery}
 *     />
 *
 *     <{{ model_name }}Table
 *       data={table.data}
 *       loading={table.loading}
 *       sorting={table.sorting}
 *       selection={table.selection}
 *       onRowClick={table.handleRowClick}
 *     />
 *
 *     <Pagination
 *       page={table.pagination.page}
 *       totalPages={table.pagination.totalPages}
 *       onPageChange={table.pagination.setPage}
 *     />
 *   </div>
 * );
 * ```
 *
 * ⚠️ AUTO-GENERATED BY PRISM - DO NOT EDIT
 */

import { useEffect, useMemo, useCallback } from 'react';
import type { {{ model_name }} } from '../types/generated';
import { use{{ model_name }}List, use{{ model_name }}Mutations } from './use{{ model_name }}';
import {
  usePagination,
  useSelection,
  useSorting,
  useSearch,
  type UsePaginationResult,
  type UseSelectionResult,
  type UseSortingResult,
  type UseSearchResult,
  type SortDirection,
} from '../prism/headless';

// ============================================================================
// Types
// ============================================================================

/** Valid sort fields for {{ model_name }} */
export type {{ model_name }}SortField = {{ sort_fields_type }};

/** Table state hook options */
export interface Use{{ model_name }}TableStateOptions {
  /** Initial page size */
  initialPageSize?: number;
  /** Whether to enable row selection */
  enableSelection?: boolean;
  /** Initial sort configuration */
  initialSort?: {
    field: {{ model_name }}SortField;
    direction: SortDirection;
  };
  /** Search debounce delay in ms */
  searchDebounceMs?: number;
  /** Fields to search in (for client-side search fallback) */
  searchFields?: {{ model_name }}SortField[];
  /** Callback when row is clicked */
  onRowClick?: (item: {{ model_name }}) => void;
}

/** Table state */
export interface {{ model_name }}TableState {
  /** Current table data */
  data: {{ model_name }}[];
  /** Loading state */
  loading: boolean;
  /** Error state */
  error: Error | null;
  /** Total count of items */
  totalCount: number;
  /** Whether data is empty */
  isEmpty: boolean;
  /** Pagination state and actions */
  pagination: UsePaginationResult;
  /** Selection state and actions (if enabled) */
  selection: UseSelectionResult<{{ model_name }}>;
  /** Sorting state and actions */
  sorting: UseSortingResult<{{ model_name }}SortField>;
  /** Search state and actions */
  search: UseSearchResult;
}

/** Table actions */
export interface {{ model_name }}TableActions {
  /** Refetch data */
  refetch: () => void;
  /** Handle row click */
  handleRowClick: (item: {{ model_name }}) => void;
  /** Delete a single item */
  deleteItem: (id: number) => Promise<boolean>;
  /** Delete selected items */
  deleteSelected: () => Promise<void>;
  /** Reset all table state */
  reset: () => void;
}

/** Combined table state and actions */
export type Use{{ model_name }}TableStateResult = {{ model_name }}TableState & {{ model_name }}TableActions;

// ============================================================================
// Hook Implementation
// ============================================================================

/**
 * Hook for managing {{ model_name }} table state.
 *
 * @param options - Table state options
 * @returns Table state and actions
 */
export function use{{ model_name }}TableState(
  options: Use{{ model_name }}TableStateOptions = {}
): Use{{ model_name }}TableStateResult {
  const {
    initialPageSize = 20,
    enableSelection = false,
    initialSort,
    searchDebounceMs = 300,
    searchFields = {{ default_search_fields }},
    onRowClick,
  } = options;

  // Composable hooks
  const pagination = usePagination({
    initialPageSize,
  });

  const selection = useSelection<{{ model_name }}>({
    keyExtractor: (item) => item.id,
  });

  const sorting = useSorting<{{ model_name }}SortField>({
    initialField: initialSort?.field,
    initialDirection: initialSort?.direction,
  });

  const search = useSearch({
    debounceMs: searchDebounceMs,
  });

  // Data fetching
  const {
    data: rawData,
    loading,
    error,
    totalCount: rawTotalCount,
    refetch,
  } = use{{ model_name }}List({
    page: pagination.page,
    pageSize: pagination.pageSize,
  });

  const { remove } = use{{ model_name }}Mutations();

  // Update pagination total when data changes
  useEffect(() => {
    pagination.setTotalItems(rawTotalCount);
  }, [rawTotalCount, pagination.setTotalItems]);

  // Apply client-side search if query exists
  // (ideally this would be server-side, but this provides a fallback)
  const data = useMemo(() => {
    if (!search.debouncedQuery || searchFields.length === 0) {
      return rawData;
    }

    const query = search.debouncedQuery.toLowerCase();
    return rawData.filter((item) =>
      searchFields.some((field) => {
        const value = item[field as keyof {{ model_name }}];
        if (value === null || value === undefined) return false;
        return String(value).toLowerCase().includes(query);
      })
    );
  }, [rawData, search.debouncedQuery, searchFields]);

  // Computed state
  const totalCount = search.debouncedQuery ? data.length : rawTotalCount;
  const isEmpty = data.length === 0 && !loading;

  // Actions
  const handleRowClick = useCallback(
    (item: {{ model_name }}) => {
      onRowClick?.(item);
    },
    [onRowClick]
  );

  const deleteItem = useCallback(
    async (id: number): Promise<boolean> => {
      const success = await remove(id);
      if (success) {
        refetch();
      }
      return success;
    },
    [remove, refetch]
  );

  const deleteSelected = useCallback(async () => {
    const ids = selection.selected.map((item) => item.id);
    for (const id of ids) {
      await remove(id);
    }
    selection.deselectAll();
    refetch();
  }, [selection, remove, refetch]);

  const reset = useCallback(() => {
    pagination.reset();
    selection.reset();
    sorting.reset();
    search.reset();
  }, [pagination, selection, sorting, search]);

  // Build state object
  const state: {{ model_name }}TableState = {
    data,
    loading,
    error,
    totalCount,
    isEmpty,
    pagination,
    selection,
    sorting,
    search,
  };

  // Build actions object
  const actions: {{ model_name }}TableActions = {
    refetch,
    handleRowClick,
    deleteItem,
    deleteSelected,
    reset,
  };

  return {
    ...state,
    ...actions,
  };
}

export default use{{ model_name }}TableState;
