import { Box, Stack, TextField, FormControl, FormControlLabel, Checkbox, Button } from '@mui/material';
import React, { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { createCategory } from '../../api/api';
import Title from '../../components/Title';

function CreateCategory() {
  const [name, setName] = useState('');
  const [subcategoryName, setSubcategoryName] = useState('');
  const [checked, setChecked] = useState(false);
  const navigate = useNavigate();

  const handleChange = (event) => {
    setChecked(event.target.checked);
  };

  const newCategory = {
    name,
    parent: null,
    subCategories: subcategoryName.length > 0 ? [{
      name: subcategoryName
    }] : [],
  }

  console.log(newCategory);

  const dispatch = useDispatch();

  const handleSubmit = (category) => {
    dispatch(createCategory(category));
    navigate('/admin/categories');
  }

  return (
    <Box sx={{ maxWidth: '500px', m: '20px auto' }} >
      <Title>Create category</Title>
      <Box component='form' onSubmit={handleSubmit}>
        <Stack spacing={2}>
          <TextField
            value={name}
            onChange={(e) => setName(e.target.value)}
            label='Category name'
          />
          <FormControl>
            <FormControlLabel value="subCategories" control={<Checkbox checked={checked} onChange={handleChange} />} label="Subcategories" />
          </FormControl>
          <TextField
            disabled={!checked}
            value={subcategoryName}
            onChange={(e) => setSubcategoryName(e.target.value)}
            label='Subcategory name'
          />
          <Button onClick={() => handleSubmit(newCategory)}>Add</Button>
        </Stack>
      </Box>
    </Box>

  )
}

export default CreateCategory;