import { useState, useEffect } from 'react';
import Modal from '../../../components/common/Modal/Modal';
import {
  Box,
  FormControl,
  Button,
  TextField,
  Typography,
  FormControlLabel,
  Radio,
  RadioGroup,
} from '@mui/material';
import { UsersApi } from '../../../api/users';
import { AutocompleteForChangeOptions } from '../components/AutocompleteForChangeOptions';
import { toast } from 'react-toastify';

export const ModalAddSsp = ({ open, onClose, onSave }) => {
  const [title, setTitle] = useState('');
  const [type, setType] = useState('ssp');
  const [usersData, setUsersData] = useState({ update: [], delete: [] });
  const [allUsers, setAllUsers] = useState([]);
  
  useEffect(() => {
    if (!open) {
      setTitle('');
      setType('ssp');
      setUsersData({ update: [], delete: [] });
    }
  }, [open]);

  useEffect(() => {
    UsersApi.getAll()
      .then((data) => {
        if (data.success) {
          setAllUsers(data.result);
          return;
        }
        toast.error('Ошибка получения всех пользователей ' + data.message);
      })
      .catch(() => {
        toast.error('Ошибка получения всех пользователей');
      });
  }, []);

  const handleClickSave = () => {
    const saveSsp = {
      title: title,
      is_ssp: type === 'ssp',
    };

    onSave?.(saveSsp, usersData);
    onClose();
  };

  const handleTypeChange = (e) => {
    setType(e.target.value);
  };

  return (
    <Modal
      title={'Добавить ССП/Рег. филиал'}
      open={open}
      onClose={onClose}
      actions={
        <>
          <Button 
            variant="grey" 
            onClick={onClose} 
            sx={{ height: '2.5rem' }}
          >
            Отменить
          </Button>
          <Button
            variant="contained"
            onClick={handleClickSave}
            sx={{ height: '2.5rem' }}
          >
            Сохранить
          </Button>
        </>
      }
    >
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: '0.5rem' }}>
          <Typography
            sx={{
              fontWeight: '400',
              fontSize: '0.88rem',
              color: '#4a5565',
              lineHeight: '1.2',
            }}
          >
            Название
          </Typography>

          <TextField
            variant="outlined"
            placeholder="Введите название"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            size="small"
            sx={{
              '& .MuiOutlinedInput-root': {
                height: '2rem',
                fontSize: '0.875rem',
                '& fieldset': {
                  borderRadius: '0.5rem',
                  border: '1px solid rgba(0,0,0,0.1)',
                },
              },
              '& .MuiInputBase-input': {
                padding: '0 0.875rem',
                height: '100%',
              },
            }}
          />

          {/* Выбор типа */}
          <FormControl component="fieldset" sx={{ mt: 0.5 }}>
            <RadioGroup
              row
              value={type}
              onChange={handleTypeChange}
              sx={{ gap: '1.5rem', flexDirection: 'row' }}
            >
              <FormControlLabel
                value="ssp"
                control={<Radio size="small" />}
                label={
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                    <Typography sx={{ fontSize: '0.875rem' }}>ССП</Typography>
                  </Box>
                }
              />
              <FormControlLabel
                value="regional"
                control={<Radio size="small" />}
                label={
                  <Box sx={{ display: 'flex', alignItems: 'center', gap: '0.5rem' }}>
                    <Typography sx={{ fontSize: '0.875rem' }}>
                      Региональный филиал
                    </Typography>
                  </Box>
                }
              />
            </RadioGroup>
          </FormControl>
        </Box>
        <AutocompleteForChangeOptions
          onChange={setUsersData}
          values={usersData.update}
          options={allUsers}
        />
      </Box>
    </Modal>
  );
};