import { useMemo, useCallback } from 'react';
import { useTableColumnStore, usePageColumnSettings } from '@/stores/useTableColumnStore';
import type { TableColumn } from '@/components/templates/UniversalListPage/types';

export interface ColumnWithVisibility extends TableColumn {
  visible: boolean;
  locked: boolean;
}

interface UseColumnSettingsParams {
  pageId: string;
  columns: TableColumn[];
  alwaysVisibleKeys?: string[];
}

export function useColumnSettings({ pageId, columns, alwaysVisibleKeys = [] }: UseColumnSettingsParams) {
  const settings = usePageColumnSettings(pageId);
  const setColumnWidthAction = useTableColumnStore((s) => s.setColumnWidth);
  const toggleColumnVisibilityAction = useTableColumnStore((s) => s.toggleColumnVisibility);
  const resetPageSettingsAction = useTableColumnStore((s) => s.resetPageSettings);

  const visibleColumns = useMemo(() => {
    return columns.filter((col) =>
      alwaysVisibleKeys.includes(col.key) || !settings.hiddenColumns.includes(col.key)
    );
  }, [columns, settings.hiddenColumns, alwaysVisibleKeys]);

  const allColumnsWithVisibility = useMemo((): ColumnWithVisibility[] => {
    return columns.map((col) => ({
      ...col,
      visible: alwaysVisibleKeys.includes(col.key) || !settings.hiddenColumns.includes(col.key),
      locked: alwaysVisibleKeys.includes(col.key),
    }));
  }, [columns, settings.hiddenColumns, alwaysVisibleKeys]);

  const columnWidths = settings.columnWidths;

  const setColumnWidth = useCallback(
    (key: string, width: number) => {
      setColumnWidthAction(pageId, key, width);
    },
    [setColumnWidthAction, pageId]
  );

  const toggleColumnVisibility = useCallback(
    (key: string) => {
      if (alwaysVisibleKeys.includes(key)) return;
      toggleColumnVisibilityAction(pageId, key);
    },
    [toggleColumnVisibilityAction, pageId, alwaysVisibleKeys]
  );

  const resetSettings = useCallback(() => {
    resetPageSettingsAction(pageId);
  }, [resetPageSettingsAction, pageId]);

  const hasHiddenColumns = settings.hiddenColumns.length > 0;

  return {
    visibleColumns,
    allColumnsWithVisibility,
    columnWidths,
    setColumnWidth,
    toggleColumnVisibility,
    resetSettings,
    hasHiddenColumns,
  };
}
