import { useState } from 'react';

import Box from '@mui/material/Box';
import Modal from '@mui/material/Modal';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';

import { Iconify } from 'src/components/iconify/iconify';

import { createAttributes, filterTypes, Type } from '../../../services/attribute-service';

const style = {
  position: 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  width: 400,
  bgcolor: 'background.paper',
  boxShadow: 24,
  p: 4,
};

type ModalProps = {
  open: boolean;
  handleClose: () => void;
}

export default function CreateFilterModal({ open, handleClose }: ModalProps) {
  const [name, setName] = useState<string | undefined>('');
  const [label, setLabel] = useState<string | undefined>('');
  const [selectedType, setSelectedType] = useState<Type | null>(null);

  function closeReset() {
    handleClose();
    setName('');
    setLabel('')
    setSelectedType(null)
  }

  async function tryCreateFilter(): Promise<any> {
    if (!name) {
      alert('No name.');
    }
    else if (!selectedType) {
      alert('No type.');
    }
    else {
      await createAttributes({ name: name, type: selectedType, label: label }).then(closeReset);
    }
  }

  return (
    <Modal
      open={open}
      onClose={closeReset}
      aria-labelledby="modal-modal-title"
      aria-describedby="modal-modal-description"
    >
      <Box sx={style}>
        <TextField label="Label" variant="filled" value={name} onChange={e => setName(e.target.value)} />
        <TextField label="Name" variant="filled" value={label} onChange={e => setLabel(e.target.value)} />
        <Autocomplete
          disablePortal
          options={filterTypes}
          value={selectedType}
          onChange={(event, newValue) => setSelectedType(newValue)}
          renderInput={params => <TextField {...params} label="Type" variant="filled" />}
        />
        <Button
          variant="contained"
          color="inherit"
          startIcon={<Iconify icon="mingcute:add-line" />}
          onClick={() => tryCreateFilter()}
        >
          Add filter
        </Button>
      </Box>
    </Modal>
  );
}
