import { SubmitHandler, useForm } from 'react-hook-form';
import { IRoleCreate } from '../../interfaces/role';
import RoleService from '../../services/RoleService';
import { Box, Button, Modal, TextField, Typography } from '@mui/material';

interface Props {
  open: boolean;
  setOpen: (state: boolean) => void;
}

const style = {
  position: 'absolute',
  top: '50%',
  left: '50%',
  transform: 'translate(-50%, -50%)',
  width: 400,
  bgcolor: 'background.paper',
  boxShadow: 24,
  borderRadius: 2,
  p: 4,
  display: "flex",
  flexDirection: "column",
  gap: "8px"
}

export default function CreateRoleModal({
  open,
  setOpen
}: Props) {
  const { register, handleSubmit, formState: { errors } } = useForm<IRoleCreate>({
    defaultValues: {
      name: '',
      description: ''
    }
  })

  const onSubmit: SubmitHandler<IRoleCreate> = async (data) => {
    try {
      await RoleService.createRole(data)
    } catch (error) {
      console.error(error)
    }
  }

  return (
    <Modal
      open={open}
      onClose={() => setOpen(false)}
      aria-labelledby="modal-modal-title"
      aria-describedby="modal-modal-description"
    >
      <form onSubmit={handleSubmit(onSubmit)}>
        <Box sx={style}>
          <Typography variant="h6" component="h6" gutterBottom>
            Создание роли
          </Typography>

          <TextField
            fullWidth
            margin="normal"
            label="Название"
            required
            {...register('name', { required: 'Название обязательно' })}
            error={!!errors.name}
            helperText={errors.name?.message}
          />

          <TextField
            fullWidth
            margin="normal"
            label="Описание"
            {...register('description')}
            error={!!errors.description}
            helperText={errors.description?.message}
          />

          <Box sx={{
            display: "flex",
            justifyContent: "space-between",
            gap: "8px"
          }}>
            <Button type="submit" variant="contained" color="primary">
              Добавить роль
            </Button>

            <Button type="button" variant="outlined" color="primary" onClick={() => setOpen(false)}>
              Отмена
            </Button>
          </Box>
        </Box>
      </form>
    </Modal>
  )
}