import { Box, Button, Checkbox, FormControl, InputLabel, ListItemText, MenuItem, OutlinedInput, Select, Stack, TextField } from '@mui/material';
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { createCategory, useGetCategoriesQuery } from '../api/api';

const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
  PaperProps: {
    style: {
      maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
      width: 250,
    },
  },
};

function EditCategory({buttonText, nameCategory, subCategories, categoryId}) {
  const { data } = useGetCategoriesQuery();
  const [name, setName] = useState(nameCategory || '');
  const [selectedCategories, setSelectedCategories] = useState(subCategories || []);

  const navigate = useNavigate();

  const dispatch = useDispatch();

  const handleChange = (event) => {
    setSelectedCategories([...event.target.value]);
  };

  const category = {
    name,
    parent: null,
    subCategories: selectedCategories,
  }
  if (categoryId) {
    category._id = categoryId;
  }

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

  return (
    <Box component='form' onSubmit={handleSubmit}>
      <Stack >
        <TextField
          sx={{ m: '0 auto 20px', width: '100%' }}
          value={name}
          onChange={(e) => setName(e.target.value)}
          label='Category name'
        />
        <FormControl
          sx={{ m: '0 auto 20px', width: '100%' }}>
          <InputLabel>Subcategories</InputLabel>
          <Select
            multiple
            value={selectedCategories}
            onChange={handleChange}
            input={<OutlinedInput label="Category name" />}
            renderValue={(selected) => selected.map(item => item.name).join(', ')}
            MenuProps={MenuProps}
          >
            {data?.CategoryFind?.map((category) => (
              <MenuItem key={category._id} value={category}>
                <Checkbox checked={selectedCategories?.indexOf(category) > -1} />
                <ListItemText primary={category.name} />
              </MenuItem>
            ))}
          </Select>
        </FormControl>
        <Button sx={{ maxWidth: '200px', width: '100%', mx: 'auto' }} onClick={() => handleSubmit(category)}>{buttonText}</Button>
      </Stack>
    </Box>
  )
}

export default EditCategory;