import { useEffect, useState } from 'react';
import {
  Box,
  Button,
  Divider,
  FormControl,
  FormLabel,
  IconButton,
  Stack,
  TextField,
  Select,
  MenuItem,
  Autocomplete,
} from '@mui/material';
import {
  ModalBackdrop,
  ModalContainer,
  HeaderContainer,
  ModalTitle,
} from './Modal.styles';
import { CalendarInput } from './Calendar/CalendarInput';
import { Cancel } from '../common/icons/icons';
import { getStageStatus, getStatusColors } from './StagesTable/utils';
import { StageStatusChip } from './StageStatusChip';
import { formatDateForApi } from '../../utils/formatDate';
import { stageColumnsHiddenFromPicker } from './constants';
import CollapsibleTree from '../common/CollapsibleTree';
import { collectLeafColumns } from '../RealtimeTable/utils/columnUtils';
import { STAGE_ROLE_RUSSIAN_NAME } from '../../constants/constants';

export const AddStagesModal = ({
  isOpen,
  onClose,
  stage = null,
  createStage,
  updateStage,
  isTaskMode = false,
  isSaving = false,
  sheetOptions = [], // [{ value: 'sheet1', label: 'Лист 1' }]
  formType = '',
  defaultSheet = '',
}) => {
  const [startDate, setStartDate] = useState(null);
  const [endDate, setEndDate] = useState(null);
  const [stageName, setStageName] = useState('');
  const [selectedSheet, setSelectedSheet] = useState(defaultSheet);
  const [selectedRole, setSelectedRole] = useState();
  const [columnsConfig, setColumnsConfig] = useState({ columns: [], colors: {} });
  const [selectedColumns, setSelectedColumns] = useState([]);

  useEffect(() => {
    const loadColumnsConfig = async () => {
      if (!selectedSheet) return;
      const sheetObj = sheetOptions.find(s => s.value == selectedSheet);

      try {
        const { config } = await import(`../RealtimeTable/constants/${formType}/${sheetObj.sheet}.js`);
        setColumnsConfig(config.config);
      } catch (error) {
        console.error(`Failed to load config for ${formType}/${selectedSheet}:`, error);
        setColumnsConfig({ columns: [], colors: {} });
      }
    };

    loadColumnsConfig();
  }, [selectedSheet, formType, stage]);

  useEffect(() => {
    if (stage !== null) {
      setStartDate(stage.opens_at ?? null);
      setEndDate(stage.closes_at ?? null);
      setStageName(stage.phase_code ?? '');
      setSelectedSheet(stage.sheet ?? null);
      setSelectedRole(stage.role ?? null);
      setSelectedColumns(stage.column_keys.map(c => 'data.' + c));
    } else {
      setStartDate(null);
      setEndDate(null);
      setStageName('');
      setSelectedSheet(defaultSheet);
      setSelectedRole();
      setSelectedColumns([]);
    }
  }, [stage, isOpen, defaultSheet]);

  const handleSave = () => {
    const opensAt = formatDateForApi(startDate);
    const closesAt = formatDateForApi(endDate);
    const sheetObj = sheetOptions.find(s => s.value == selectedSheet);

    const stageData = {
      phase_code: stageName,
      sheet: sheetObj.sheet,
      direction: sheetObj.direction,
      role: selectedRole,
      opens_at: opensAt,
      closes_at: closesAt,
      column_keys: selectedColumns.map(c => c.slice(5)),
    };

    if (stage === null) {
      if (!createStage) return;
      createStage(stageData)?.then(() => {
        handleCancel();
      });
    } else {
      updateStage({
        ...stage,
        ...stageData,
      })?.then(() => {
        handleCancel();
      });
    }
  };

  const handleCancel = () => {
    setStartDate(null);
    setEndDate(null);
    setStageName('');
    setSelectedSheet(defaultSheet);
    setSelectedRole();
    setSelectedColumns([]);
    onClose();
  };

  const handleBackdropClick = (e) => {
    if (e.target === e.currentTarget) {
      handleCancel();
    }
  };

  const handleSheetChange = (event) => {
    setSelectedSheet(event.target.value);
    setSelectedColumns([]);
  };

  const handleColumnsSelect = (column, isSelect) => {
    const leafCols = collectLeafColumns(column).reduce((acc, item) => {
      acc.push(item.accessorKey)
      return acc;
    }, []);
    if (!isSelect) {
      setSelectedColumns(prev => ([...new Set([...prev, ...leafCols])]));
    }
    else {
      setSelectedColumns(prev => (prev.filter(c => !leafCols.includes(c))));
    }
  };

  const isFormValid = startDate && endDate && stageName.trim() && selectedSheet;

  if (!isOpen) return null;

  const stageStatus = stage ? getStageStatus(stage) : null;
  const statusColors = stageStatus ? getStatusColors(stageStatus) : null;

  const columnTree = columnsConfig.columns || [];

  return (
    <ModalBackdrop isOpen={isOpen} onClick={handleBackdropClick}>
      <ModalContainer>
        <HeaderContainer>
          <Stack direction="row" spacing={2} sx={{ alignItems: 'center' }}>
            <ModalTitle>
              {stage ? 'Редактирование этапа' : 'Добавление этапа'}
            </ModalTitle>
            {stageStatus && statusColors && (
              <StageStatusChip
                label={stageStatus}
                bg={statusColors.bg}
                color={statusColors.color}
                border={statusColors.border}
              />
            )}
          </Stack>
          <IconButton size="small" onClick={handleCancel}>
            <Cancel />
          </IconButton>
        </HeaderContainer>

        <Box>
          <Divider sx={{ marginBottom: '0.75rem' }} />

          {/* Название этапа */}
          <Stack sx={{ marginBottom: '0.75rem', width: '100%' }}>
            <FormControl fullWidth>
              <FormLabel>Название этапа</FormLabel>
              <TextField
                value={stageName}
                onChange={(e) => setStageName(e.target.value)}
                placeholder="Введите название этапа"
                fullWidth
                size="small"
                disabled={stage !== null}
              />
            </FormControl>
          </Stack>

          {/* Выбор листа */}
          <Stack sx={{ marginBottom: '0.75rem', width: '100%' }}>
            <FormControl fullWidth>
              <FormLabel>Выбор листа</FormLabel>
              <Select
                value={selectedSheet}
                onChange={handleSheetChange}
                displayEmpty
                size="small"
              >
                <MenuItem value="" disabled>
                  Выберите лист
                </MenuItem>
                {sheetOptions.map((option) => (
                  <MenuItem key={option.value} value={option.value}>
                    {option.label}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Stack>
          {selectedSheet && columnTree.length > 0 && (
            <Stack sx={{ marginBottom: '0.75rem', width: '100%' }}>
              <FormControl fullWidth>
                <FormLabel>Выбор колонок</FormLabel>

                <CollapsibleTree
                  columnTree={columnTree}
                  excludeColumnKeys={stageColumnsHiddenFromPicker}
                  placeholder="Выбрать столбцы"
                  placeholderSelect="Выбрано столбцов: "
                  selectedIds={selectedColumns}
                  onSelectNode={handleColumnsSelect}
                  forStage={true}
                />
              </FormControl>
            </Stack>
          )}

          <Stack sx={{ marginBottom: '0.75rem', width: '100%' }}>
            <FormControl fullWidth>
              <FormLabel>Роль</FormLabel>
              <Select
                value={selectedRole ?? ''}
                onChange={(e) => setSelectedRole(e.target.value)}
                displayEmpty
                size="small"
              >
                {Object.entries(STAGE_ROLE_RUSSIAN_NAME).map(([key, label]) => (
                  <MenuItem key={key} value={key}>
                    {label}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </Stack>



          {/* Даты */}
          <Stack
            direction="row"
            spacing={1}
            sx={{ marginBottom: 0, width: '100%' }}
          >
            <Stack direction="column" spacing={0.5} sx={{ flex: 1 }}>
              <FormControl fullWidth>
                <FormLabel>Дата начала</FormLabel>
                <CalendarInput
                  value={startDate}
                  onChange={(newValue) => setStartDate(newValue)}
                />
              </FormControl>
            </Stack>
            <Stack direction="column" spacing={0.5} sx={{ flex: 1 }}>
              <FormControl fullWidth>
                <FormLabel>Дата окончания</FormLabel>
                <CalendarInput
                  value={endDate}
                  onChange={(newValue) => setEndDate(newValue)}
                />
              </FormControl>
            </Stack>
          </Stack>

          <Stack
            direction="row"
            spacing={0.75}
            sx={{
              justifyContent: 'flex-end',
              marginTop: '1.5rem',
              width: '100%',
            }}
          >
            <Button
              variant="outlined"
              color="default"
              onClick={handleCancel}
              style={{ height: '2.5rem' }}
              disabled={isSaving}
            >
              Отмена
            </Button>
            <Button
              variant="contained"
              onClick={handleSave}
              style={{ height: '2.5rem' }}
              disabled={!isFormValid || isSaving}
              loading={isSaving}
            >
              Сохранить
            </Button>
          </Stack>
        </Box>
      </ModalContainer>
    </ModalBackdrop>
  );
};