import { useCallback, useEffect, useMemo, useState } from 'react';
import Modal from '../../../components/common/Modal/Modal';
import { Box, Button, Typography } from '@mui/material';
import SelectWithOptions from '../components/SelectWithOptions';
import { ROLES_NAME_ID } from '../../../constants/constants';
import { AutocompleteForChangeOptions } from '../components/AutocompleteForChangeOptions';

export const ModalEditUserSsp = ({
  open,
  onClose,
  user,
  deps = [],
  onEdit,
}) => {
  const [curUser, setCurUser] = useState(user);
  const [depsData, setDepsData] = useState({ update: [], delete: [] });
  const [newDepsData, setNewDepsData] = useState({ update: [], delete: [] });
  const [ssps, setSsps] = useState([]);
  const [rfs, setRfs] = useState([]);
  const [selectedType, setSelectedType] = useState('rf'); // 'rf' или 'ssp'

  useEffect(() => {
    if (!open) {
      setCurUser(null);
      return;
    }
    setCurUser(user);
    try {
      if (user && user.role_id == ROLES_NAME_ID.executor_rf) {
        const isSsp = user.org_units?.[0]?.is_ssp;
        setSelectedType(isSsp ? 'ssp' : 'rf');
      }
    } catch {
      setSelectedType('rf');
    }
  }, [user, open]);

  useEffect(() => {
    if (!deps) return;
    const ssps = [];
    const rfs = [];
    deps.forEach((dep) => {
      if (dep.is_ssp) {
        ssps.push(dep);
        return;
      }
      rfs.push(dep);
    });
    setSsps(ssps);
    setRfs(rfs);
  }, [deps]);

  const handleChangeDepForSingle = (depId) => {
    const selectedDep = deps.find((dep) => dep.id == depId);
    if (!selectedDep) return;

    setDepsData({
      update: [selectedDep],
      delete: [...(user.org_units ?? [])],
    });

    setCurUser((prev) => ({
      ...prev,
      org_units: [selectedDep],
    }));
  };

  const handleClickSave = () => {
    onEdit(curUser, newDepsData);
    onClose();
  };

  useEffect(() => {
    const newDataDeps = {
      update: depsData.update.map((d) => d.id),
      delete: depsData.delete.map((d) => d.id),
    };
    setNewDepsData(newDataDeps);
  }, [depsData]);

  const sspForDfip = useMemo(() => {
    if (!curUser|| !open) return [];
    return curUser.org_units ?? [];
  }, [curUser, deps, newDepsData, open]);

  const handleTypeChange = (value) => {
    setSelectedType(value);
    // Сбрасываем выбранное подразделение при смене типа
    setCurUser((prev) => ({
      ...prev,
      ssp_id: null,
    }));
    setDepsData({ update: [], delete: [] });
  };

  if (!curUser) return null;

  return (
    <Modal
      title={'Выбор подразделения'}
      open={open}
      onClose={onClose}
      actions={
        <>
          <Button variant="grey" onClick={onClose} style={{ height: '2.5rem' }}>
            Отменить
          </Button>
          <Button
            variant="contained"
            onClick={handleClickSave}
            style={{ height: '2.5rem' }}
          >
            Сохранить
          </Button>
        </>
      }
    >
      {curUser.role_id == ROLES_NAME_ID['executor_dfip'] && (
        <Box>
          <Typography
            sx={{
              fontWeight: '400',
              fontSize: '0.75rem',
              color: 'var(--grey-dark)',
              paddingBottom: '.25rem',
            }}
          >
            ССП/РФ
          </Typography>
          <AutocompleteForChangeOptions
            values={sspForDfip}
            options={deps}
            onChange={setDepsData}
          />
        </Box>
      )}

      {curUser.role_id == ROLES_NAME_ID['executor_rf'] && (
        <Box>
          <Box sx={{ marginBottom: '1rem' }}>
            <Typography
              sx={{
                fontWeight: '400',
                fontSize: '0.75rem',
                color: 'var(--grey-dark)',
                paddingBottom: '.25rem',
              }}
            >
              Тип
            </Typography>
            <SelectWithOptions
              value={selectedType}
              options={[
                { value: 'rf', label: 'РФ' },
                { value: 'ssp', label: 'ССП' },
              ]}
              onChange={handleTypeChange}
              width="28.25rem"
              placeholder="Выберите тип"
            />
          </Box>

          <Box>
            <Typography
              sx={{
                fontWeight: '400',
                fontSize: '0.75rem',
                color: 'var(--grey-dark)',
                paddingBottom: '.25rem',
              }}
            >
              {selectedType === 'rf' ? 'РФ' : 'ССП'}
            </Typography>
            <SelectWithOptions
              value={curUser.org_units?.[0]?.id}
              options={selectedType === 'rf' ? rfs : ssps}
              placeholder="-"
              onChange={handleChangeDepForSingle}
              width="28.25rem"
            />
          </Box>
        </Box>
      )}

      {curUser.role_id == ROLES_NAME_ID['admin'] && (
        <Box>
          <Typography
            sx={{
              fontWeight: '400',
              fontSize: '0.75rem',
              color: 'var(--grey-dark)',
              paddingBottom: '.25rem',
            }}
          >
            ССП/РФ
          </Typography>
          <SelectWithOptions
            value={curUser.org_units?.[0]?.id}
            placeholder="-"
            options={deps}
            onChange={handleChangeDepForSingle}
            width="28.25rem"
          />
        </Box>
      )}
    </Modal>
  );
};
