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 './CollapsibleTree';
import ZoomSlider from './ZoomSlider';
import SearchComponent from '../../common/SearchComponent';
import { ExportDefaultButton } from '../../common/Buttons/ButtonsActions';
import { exportSheet } from '../../../utils/exportForm';

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

  useEffect(() => {
    if (!table) return;
    setColumnTree(table.getAllColumns());
    setShowColumnFilters(table.getState().showColumnFilters);
  }, [table, isLoadingData]);

  useEffect(() => {
    if (!selectedColumn) return;
    const pinningColumn = table.getState().columnPinning.left;
    const isPinned = pinningColumn.includes(selectedColumn.id);
    setIsPinned(isPinned);
  }, [selectedColumn, 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 (!formId || !sheetName || isExporting) return;
    setIsExporting(true);
    await exportSheet(formId, sheetName, direction);
    setIsExporting(false);
  };

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

            <Tooltip title="Закрепить область">
              <IconButton
                variant="outlined"
                data-active={isPinned}
                onClick={() =>
                  isPinned
                    ? onUnpinColumn?.(selectedColumn.id)
                    : onPinColumn?.(selectedColumn.id)
                }
              >
                <Pin />
              </IconButton>
            </Tooltip>
          </GroupByObject>

          <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="Формулы">
            <Tooltip title="Добавить формулу">
              <IconButton onClick={handleClickAddFormula} variant="outlined">
                <FormulaSettingPanel />
              </IconButton>
            </Tooltip>

            <Tooltip title="Удалить формулу">
              <IconButton onClick={handleClickDeleteFormula} variant="outlined">
                <Minus />
                <FormulaSettingPanel />
              </IconButton>
            </Tooltip>
          </GroupByObject>
          <Divider orientation="vertical" flexItem />
          <GroupByObject title="Столбцы">
            {columnTree ? (
              <CollapsibleTree
                columnTree={columnTree}
                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 ? 'Экспорт...' : 'Экспорт в Excel'}
            />
          </GroupByObject>
        </Stack>
      </Panel>
    </>
  );
};

export default SettingPanel;
