import { useState, useEffect, useCallback } from 'react';
import { loadFromStorage, saveToStorage } from '../utils/localStorageUtils.js';
import { getLeafColumns, collectLeafColumns } from '../utils/columnUtils';
import { columnPinningDefault, columnVisibilityDefault } from '../constants/columnConfig.js';

export const useColumnSettings = (tableKey) => {
  const getStorageKey = (key) => tableKey ? `${tableKey}_${key}` : key;

  const [columnSizing, setColumnSizing] = useState(() =>
    loadFromStorage(getStorageKey('columnSizing'), {}),
  );
  const [columnPinning, setColumnPinning] = useState(() =>
    loadFromStorage(getStorageKey('columnPinning'), columnPinningDefault),
  );
  const [columnVisibility, setColumnVisibility] = useState(() =>
    loadFromStorage(getStorageKey('columnVisibility'), columnVisibilityDefault),
  );

  // Сохранение в localStorage
  useEffect(() => {
    saveToStorage(getStorageKey('columnSizing'), columnSizing);
  }, [columnSizing, tableKey]);

  useEffect(() => {
    saveToStorage(getStorageKey('columnPinning'), columnPinning);
  }, [columnPinning, tableKey]);

  useEffect(() => {
    saveToStorage(getStorageKey('columnVisibility'), columnVisibility);
  }, [columnVisibility, tableKey]);

  // Сброс настроек при изменении tableKey (опционально)
  useEffect(() => {
    setColumnSizing(loadFromStorage(getStorageKey('columnSizing'), {}));
    setColumnPinning(loadFromStorage(getStorageKey('columnPinning'), columnPinningDefault));
    setColumnVisibility(loadFromStorage(getStorageKey('columnVisibility'), columnVisibilityDefault));
  }, [tableKey]);

  const handlePinColumn = useCallback((colId) => {
    setColumnPinning((prev) => ({ ...prev, left: [...prev.left, colId] }));
  }, []);

  const handleUnpinColumn = useCallback((colId) => {
    if (!colId) return;
    if (columnPinningDefault.left.includes(colId)) return;
    setColumnPinning((prev) => ({
      ...prev,
      left: prev.left.filter((c) => c !== colId),
    }));
  }, []);

  const handleSetColumnWidth = useCallback((column, newWidth) => {
    const columnsResize = getLeafColumns(column);
    const widthDiff =
      (column.getSize() - parseFloat(newWidth)) / columnsResize.length;

    const newColumnSizing = {};
    for (const col of columnsResize) {
      newColumnSizing[col.id] = col.getSize() - widthDiff;
    }

    setColumnSizing((prev) => ({ ...prev, ...newColumnSizing }));
  }, []);

  const handleToggleColumnVisibility = useCallback((column, isSelect) => {
    const leafCols = collectLeafColumns(column).reduce((acc, item) => {
      acc[item.id] = isSelect;
      return acc;
    }, {});

    setColumnVisibility((prev) => ({ ...prev, ...leafCols }));
  }, []);

  // Опционально: функция для сброса всех настроек
  const resetAllSettings = useCallback(() => {
    setColumnSizing({});
    setColumnPinning(columnPinningDefault);
    setColumnVisibility(columnVisibilityDefault);
  }, []);

  return {
    columnSizing,
    columnPinning,
    columnVisibility,
    setColumnSizing,
    setColumnPinning,
    setColumnVisibility,
    handlePinColumn,
    handleUnpinColumn,
    handleSetColumnWidth,
    handleToggleColumnVisibility,
    resetAllSettings, // добавляем функцию сброса
    tableKey, // опционально возвращаем tableKey
  };
};