import * as React from 'react';
import {Button, Checkbox, Grid, Switch, TextField} from "@mui/material";
import Autocomplete from "@mui/material/Autocomplete";
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import {SetCount} from "../../components/SetCount";
import {connect} from "react-redux";
import {actionCategoryCount, actionCategoryUpsert, actionFullRootCats} from "../../actions/ActionCategory";
import {actionAllGoodFind} from "../../actions/ActionGoodFind";
import { enableRipple } from '@syncfusion/ej2-base';
import { TreeViewComponent } from '@syncfusion/ej2-react-navigations';
import {useEffect, useState} from "react";
enableRipple(true);

const InputCategory = ({goods, setArray, countSubCat}) => {
    const [name, setName] = useState('');
    const [products, setProducts] = useState([]);
    const [addSub, setAddSub] = useState(false);
    const [subArray, setSubArray] = useState([]);

    const [checked, setChecked] = useState(false);
    const handleChange = (event) => {
        setChecked(event.target.checked);
        if (!checked){
            setArray([{"name": name, "goods": products, "subcategory": subArray}])
        }
    };

    return (
        <>
            <Grid container justifyContent='space-between'>
                <Grid item xs={5}>
                    <TextField fullWidth id="filled-basic" label="Title category" variant="standard" value={name} onChange={e => {setName(e.target.value); setChecked(false)}}/>
                </Grid>
                <Grid item xs={5}>
                    {goods?.payload &&
                        <Autocomplete
                            multiple
                            id="tags-standard"
                            options={goods.payload}
                            onChange={(event, newValue) => {
                                setProducts([newValue]);
                                setChecked(false)
                            }}
                            getOptionLabel={(option) => option?.name || 'no name'}
                            key={option => option?.id}
                            renderInput={(params) => (
                                <TextField
                                    {...params}
                                    variant="standard"
                                    label="Select goods"
                                    placeholder="goods"
                                />
                            )}
                        />
                    }
                </Grid>
                <Grid item xs={1} display='flex' justifyContent='center' alignItems='flex-end'>
                    <Checkbox
                        checked={checked}
                        onChange={handleChange}
                        inputProps={{ 'aria-label': 'controlled' }}
                    />
                </Grid>
            </Grid>
            <Grid container justifyContent='space-between' marginTop='30px' marginBottom='10px'>
                <Grid item xs={5.5}>
                    {countSubCat < 2 &&
                        <Box display='flex' alignItems='center'>
                            <Typography color='#616161'>Add subcategories</Typography>
                            <Switch onChange={() => {setAddSub(!addSub); setChecked(false)}}/>
                        </Box>
                    }
                </Grid>
            </Grid>
            {addSub && <AddCategory goods={goods} setArray={value => setSubArray(value)} addCategory={true} countSubCat={countSubCat+1}/>}
        </>
    )
}
const AddCategory = ({goods, setArray, addCategory, countSubCat}) => {
    const [name, setName] = useState('');
    const [products, setProducts] = useState([]);
    const [addSub, setAddSub] = useState(false);
    const [subArray, setSubArray] = useState([]);
    const [addCat, setAddCat] = useState(false);
    const [catCount, setCatCount] = useState(0);
    const [subCat, setSubCat] = useState([]);

    useEffect(() => {
        setArray([{"name": name, "goods": products, "subcategory": subArray}, {...subCat}])
    }, [name, products, subArray, subCat])
    console.log(subCat)

    return (
        <Box sx={{border: '1px dashed #616161', borderRadius: '20px', padding: '20px'}}>
            <Grid container justifyContent='space-between'>
                <Grid item xs={5.5}>
                    <TextField fullWidth id="filled-basic" label="Title category" variant="standard" value={name} onChange={e => setName(e.target.value)}/>
                </Grid>
                <Grid item xs={5.5}>
                    {goods?.payload &&
                        <Autocomplete
                            multiple
                            id="tags-standard"
                            options={goods.payload}
                            onChange={(event, newValue) => {
                                setProducts([newValue]);
                            }}
                            getOptionLabel={(option) => option?.name || 'no name'}
                            key={option => option?.id}
                            renderInput={(params) => (
                                <TextField
                                    {...params}
                                    variant="standard"
                                    label="Select goods"
                                    placeholder="goods"
                                />
                            )}
                        />
                    }
                </Grid>
            </Grid>
            <Grid container justifyContent='space-between' marginTop='30px' marginBottom='10px'>
                <Grid item xs={5.5}>
                    {countSubCat < 2  &&
                        <Box display='flex' alignItems='center'>
                            <Typography color='#616161'>Add subcategories</Typography>
                            <Switch onChange={() => setAddSub(!addSub)}/>
                        </Box>
                    }
                </Grid>
                <Grid item xs={5.5} display='flex' justifyContent='space-between' alignItems='center'>
                    {addCategory &&
                        <Box display='flex' alignItems='center'>
                            <Typography color='#616161'>Add categories</Typography>
                            <Switch onChange={() => {setAddCat(!addCat); setCatCount(0)}}/>
                        </Box>
                    }
                    {addCat && <SetCount defaultValue={1} width={40} height={40} onCount={value => setCatCount(value)}/>}
                </Grid>
            </Grid>
            {addSub && <AddCategory goods={goods} setArray={value => setSubArray(value)} addCategory={true} countSubCat={countSubCat+1}/>}
            {catCount >= 1 && new Array(catCount).fill(0).map(item => {
                return <InputCategory goods={goods} setArray={value => setSubCat([...subCat, value])} countSubCat={countSubCat}/>
            })
            }
        </Box>
    )
}
const CategoryEdit = ({category, categoryCount, goods, variant='create', actionRootCat, getCountCategory, getGoodFind, onCreateCategory}) => {
    const [array, setArray] = useState([])

    useEffect(() => {
        if(!goods) getGoodFind()
        if(!category) actionRootCat()
        if(!categoryCount) getCountCategory()
    }, [actionRootCat, category, categoryCount, getCountCategory, getGoodFind, goods])

    return(
        <>
            <Typography variant='h6' letterSpacing='2px' marginBottom='20px'>Total category: {categoryCount?.payload || 0}</Typography>
            <AddCategory goods={goods} setArray={value => setArray(value)} countSubCat={0}/>
            <Grid container justifyContent='center' marginTop='30px'>
                <Grid item xs={4}>
                    <Button disabled={array.length === 0} fullWidth variant="outlined" onClick={() => onCreateCategory(array)}>
                        Save
                    </Button>
                </Grid>
            </Grid>
        </>
    )
}
export const CCategoryEdit = connect(state => ({category: state.category, categoryCount: state.promise['categoryCount'], goods: state.promise['goodAllFind'] }), {actionRootCat: actionFullRootCats, getCountCategory: actionCategoryCount, getGoodFind: actionAllGoodFind, onCreateCategory: actionCategoryUpsert})(CategoryEdit)


export class CCategoryEditTree extends React.Component {
    constructor() {
        super(...arguments);
        this.productTeam = [
            {
                id: 1, name: 'ASP.NET MVC Team', expanded: true,
                child: [
                    { id: 2, pid: 1, name: 'Smith', isSelected: true },
                    { id: 3, pid: 1, name: 'Johnson', isSelected: true },
                    { id: 4, pid: 1, name: 'Anderson' },
                ]
            },
            {
                id: 5, name: 'Windows Team',
                child: [
                    { id: 6, pid: 5, name: 'Clark' },
                    { id: 7, pid: 5, name: 'Wright' },
                    { id: 8, pid: 5, name: 'Lopez' },
                ]
            },
            {
                id: 9, name: 'Web Team',
                child: [
                    { id: 11, pid: 9, name: 'Joshua' },
                    { id: 12, pid: 9, name: 'Matthew' },
                    { id: 13, pid: 9, name: 'David' },
                ]
            },
            {
                id: 14, name: 'Build Team',
                child: [
                    { id: 15, pid: 14, name: 'Ryan' },
                    { id: 16, pid: 14, name: 'Justin' },
                    { id: 17, pid: 14, name: 'Robert' },
                ]
            },
            {
                id: 18, name: 'WPF Team',
                child: [
                    { id: 19, pid: 18, name: 'Brown' },
                    { id: 20, pid: 18, name: 'Johnson' },
                    { id: 21, pid: 18, name: 'Miller' },
                ]
            }
        ];
        this.fields = { dataSource: this.productTeam, id: 'id', parentID: 'pid', text: 'name', hasChildren: 'hasChild', selected: 'isSelected' };
        this.allowDragAndDrop = true;
        this.allowMultiSelection = true;
    }
    render() {
        return (
            <TreeViewComponent fields={this.fields} allowMultiSelection={this.allowMultiSelection} allowDragAndDrop={this.allowDragAndDrop}/>
        );
    }
}
