import { useEffect, useState } from 'react';
import { toast } from 'react-toastify';
import { Panel } from './SettingPanel.style';
import { Divider, IconButton, Stack, Tooltip } from '@mui/material';

import { GroupByObject } from './GroupByObject/GroupByObject';
import { ColorPickerButton } from './ColorPicker/ColorPickerButton';
import {
  AddLine,
  FormulaSettingPanel,
  Minus,
  Pin,
  Plus,
  RemoveLine,
  Search,
} from '../../common/icons/icons';
import CollapsibleTree from '../../common/CollapsibleTree';
import ZoomSlider from './ZoomSlider';
import SearchComponent from '../../common/SearchComponent';
import { ExportDefaultButton } from '../../common/Buttons/ButtonsActions';
import { exportSheet, exportSheetProject } from '../../../utils/exportFile';

const SettingPanel = ({
  selectedColumnId,
  columnPinning,
  table,
  columns,
  onPinColumn,
  onUnpinColumn,
  onToggleColumnVisibility,
  columnVisibility,
  onChangeSizeMult,
  onGlobalFilterChange,
  sizeMult,
  onChangeShowColumnFilters,
  onAddRow,
  onDeleteRow,
  isLoadingData,
  formId,
  sheetName,
  direction,
  year,
  isProject,
}) => {
  const [isPinned, setIsPinned] = useState(false);
  const [isExporting, setIsExporting] = useState(false);
  const [selectedColumnIds, setSelectedColumnIds] = useState();
  const [showColumnFilters, setShowColumnFilters] = useState(false);

  // TODO: console.log(!!!) везде посомтреть
  useEffect(() => {
    if (!selectedColumnId) {
      setIsPinned(false);
      return;
    }
    const pinningColumn = columnPinning?.left || table.getState().columnPinning.left || [];
    const pinned = pinningColumn.includes(selectedColumnId);
    setIsPinned(pinned);
  }, [selectedColumnId, columnPinning, table]);

  useEffect(() => {
    setSelectedColumnIds(
      Object.keys(columnVisibility).filter((key) => !columnVisibility[key]),
    );
  }, [columnVisibility]);

  //TO DO: сделать
  const { addColorForCells, addFormulaForCells, deleteFormula } = {};

  const handleChangeShowColumnFilters = () => {
    const show = table.getState().showColumnFilters;
    setShowColumnFilters(!show);
    onChangeShowColumnFilters(!show);
  };

  const handleClickAddFormula = () => { };

  const handleClickDeleteFormula = () => { };

  const handleExport = async () => {
    if (isExporting) return;
    if (isProject) {
      if (!formId || !sheetName || !year) return;
      setIsExporting(true);
      await exportSheetProject(formId, sheetName, year);
      setIsExporting(false);
      return;
    }

    if (!formId || !sheetName) return;
    setIsExporting(true);
    await exportSheet(formId, sheetName, direction);
    setIsExporting(false);
  };

  return (
    <>
      <Panel data-pin-panel>
        <Stack direction="row" sx={{ gap: '1.25rem' }}>
          <GroupByObject title="Отображение">
            {/* <ColorPickerButton onColorApply={addColorForCells} /> */}

            <Tooltip title="Закрепить область">
              <IconButton
                variant="outlined"
                data-active={isPinned}
                disabled={!selectedColumnId}
                onMouseDown={(e) => e.stopPropagation()}
                onClick={() => {
                  if (!selectedColumnId) {
                    console.warn('[ColumnPin] клик Pin: selectedColumnId пустой');
                    return;
                  }
                  console.log('[ColumnPin] клик Pin:', {
                    selectedColumnId,
                    isPinned,
                    action: isPinned ? 'unpin' : 'pin',
                  });
                  isPinned
                    ? onUnpinColumn?.(selectedColumnId)
                    : onPinColumn?.(selectedColumnId);
                }}
              >
                <Pin />
              </IconButton>
            </Tooltip>
          </GroupByObject>

          {!isProject &&
            <>
              <Divider orientation="vertical" flexItem />
              <GroupByObject title="Строки">
                <Tooltip title="Добавить строку">
                  <IconButton onClick={onAddRow} variant="outlined">
                    <Plus />
                    <AddLine />
                  </IconButton>
                </Tooltip>

                <Tooltip title="Удалить строку">
                  <IconButton onClick={onDeleteRow} variant="outlined">
                    <Minus />
                    <RemoveLine />
                  </IconButton>
                </Tooltip>
              </GroupByObject>
            </>
          }
          <Divider orientation="vertical" flexItem />
          <GroupByObject title="Столбцы">
            {columns ? (
              <CollapsibleTree
                columnTree={columns}
                onSelectNode={onToggleColumnVisibility}
                selectedIds={selectedColumnIds}
              />
            ) : (
              ''
            )}
          </GroupByObject>
          <Divider orientation="vertical" flexItem />
          <ZoomSlider onChange={onChangeSizeMult} curScale={sizeMult} />
          <Divider orientation="vertical" flexItem />
          <GroupByObject title="Поиск">
            <SearchComponent onChange={onGlobalFilterChange} height="2.5rem" />
            <Tooltip title="Поиск по колонкам">
              <IconButton
                variant="outlined"
                color="success"
                data-active={showColumnFilters}
                onClick={handleChangeShowColumnFilters}
              >
                <Search />
              </IconButton>
            </Tooltip>
          </GroupByObject>

          <Divider orientation="vertical" flexItem />

          <GroupByObject title="Экспорт">
            <ExportDefaultButton
              onClick={handleExport}
              disabled={!formId || !sheetName || isExporting}
              text={isExporting ? 'Экспорт...' : 'Экспорт'}
            />
          </GroupByObject>
        </Stack>
      </Panel>
    </>
  );
};

export default SettingPanel;
