import { useState } from 'react';
import { Box, Button, Divider, TextField, Typography } from '@mui/material';
import SelectWithOptions from '../AdminPanel/components/SelectWithOptions';
import Modal from '../../components/common/Modal/Modal';
import { PrimaryButton } from '../../components/common/Buttons/Buttons';

export const ModalCreateProject = ({
  open,
  onClose,
  onCreate,
  config = {},
}) => {
  const [projectData, setProjectData] = useState(() => {
    const initialData = {};
    Object.keys(config).forEach((key) => {
      initialData[key] = config[key].defaultValue;
    });
    return initialData;
  });

  const handleChange = (field, value) => {
    setProjectData((prev) => ({
      ...prev,
      [field]: value,
    }));
  };

  const handleClickCreate = () => {
    onCreate(projectData);
    onClose();
  };

  const handleClose = () => {
    const resetData = {};
    Object.keys(config).forEach((key) => {
      resetData[key] = config[key].defaultValue;
    });
    setProjectData(resetData);
    onClose();
  };

  const renderField = (fieldName, config) => {
    switch (config.type) {
      case 'multiselect':
        return (
          <Box key={fieldName}>
            <Typography
              className="gray-color"
              sx={{
                fontWeight: '400',
                fontSize: '0.75rem',
                paddingBottom: '.25rem',
              }}
            >
              {fieldName}
            </Typography>
            <SelectWithOptions
              className="sameSize"
              value={projectData[fieldName] || ''}
              options={config.options}
              placeholder={config.placeholder}
              onChange={(value) => handleChange(fieldName, value)}
              width="28.25rem"
            />
          </Box>
        );

      case 'text':
        return (
          <Box key={fieldName}>
            <Typography
              className="gray-color"
              sx={{
                fontWeight: '400',
                fontSize: '0.75rem',
                color: 'var(--grey-dark)',
                paddingBottom: '.25rem',
              }}
            >
              {fieldName}
            </Typography>
            <TextField
              className="sameSize"
              value={projectData[fieldName] || ''}
              onChange={(e) => handleChange(fieldName, e.target.value)}
              placeholder={config.placeholder}
              size="small"
            />
          </Box>
        );

      case 'number':
        return (
          <Box key={fieldName}>
            <Typography
              className="gray-color"
              sx={{
                fontWeight: '400',
                fontSize: '0.75rem',
                color: 'var(--grey-dark)',
                paddingBottom: '.25rem',
              }}
            >
              {fieldName}
            </Typography>
            <TextField
              className="sameSize"
              type="text"
              value={projectData[fieldName] || ''}
              onChange={(e) => {
                const inputValue = e.target.value;
                //только числа
                const isValidInput =
                  /^\d*\.?\d*$/.test(inputValue) || inputValue === '';
                if (isValidInput) {
                  handleChange(fieldName, inputValue);
                }
              }}
              placeholder={config.placeholder}
              size="small"
              slotProps={{
                htmlInput: {
                  min: config.min,
                  max: config.max || null,
                  step: config.step || 1,
                },
              }}
            />
          </Box>
        );

      default:
        return null;
    }
  };

  return (
    <Modal
      title={'Создание проекта'}
      open={open}
      onClose={handleClose}
      customSize={'43.75'}
      actions={
        <>
          <Button
            variant="grey"
            onClick={handleClose}
            style={{ height: '2.5rem' }}
          >
            Отменить
          </Button>
          <PrimaryButton
            variant="contained"
            onClick={handleClickCreate}
            style={{ height: '2.5rem' }}
          >
            Создать
          </PrimaryButton>
        </>
      }
    >
      <Divider />
      <Box
        sx={{
          m: '1.25rem 0',
          display: 'flex',
          flexDirection: 'column',
          gap: '1.25rem',
          '& .sameSize': {
            height: '2.69rem',
            minWidth: '39.75rem',
          },
          '& .gray-color': { color: '#4A5565' },
        }}
      >
        {Object.entries(config).map(([fieldName, config]) =>
          renderField(fieldName, config),
        )}
      </Box>
      <Divider />
    </Modal>
  );
};
