import {Grid, TextField,Typography} from "@mui/material";
import * as React from "react";
import {useEffect, useState} from "react";
import Autocomplete from "@mui/material/Autocomplete";
import {EVENT_REGION_COMBO, EVENT_TYPE_COMBO} from "../../utils/ComboConst";
import {LocalizationProvider} from "@mui/x-date-pickers/LocalizationProvider";
import {AdapterDayjs} from "@mui/x-date-pickers/AdapterDayjs";
import {DemoItem} from "@mui/x-date-pickers/internals/demo";
import {DatePicker} from "@mui/x-date-pickers/DatePicker";
import dayjs from "dayjs";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {GET_DIVISION_COMBO_LIST, GET_SUB_DIVISION_COMBO_LIST} from "../../utils/ApiPathConst";
import Qs from "qs";
import {getComboValueByIdList, getComboValueByLabel, getIdList, isOptionEqualToValue} from "../../utils/CommonFunction";
import {useParams} from "react-router-dom";
import LoadingComponent from "../extra-pages/LoadingComponent";

export default function EventTemplateForm({setValue,setIsReset, refTemplateData,
                                              isReset, isCollectData, applyTemplateValue,
                                              register, setIsCollectData}) {
    const params = useParams();
    const [onReady, setOnReady] = useState(false);

    const [selectedRegion, setSelectedRegion] = useState(null);
    const [selectedType, setSelectedType] = useState(null);
    const [selectedSubDivisions, setSelectedSubDivisions] = useState([]);
    const [selectedDivisions, setSelectedDivisions] = useState([]);
    const [fromDate, setFromDate] = useState(null);
    const [toDate, setToDate] = useState(null);
    const [refEvent, setRefEvent] = useState({});

    const [subDivisionList, setSubDivisionList] = useState([]);
    const [divisionList, setDivisionList] = useState([]);

    const [fromError, setFromError] = React.useState(null);
    const [toError, setToError] = React.useState(null);

    const fromErrorMessage = React.useMemo(() => {
        switch (fromError) {
            case 'invalidDate': {
                return "Please input a valid date";
            }
        }
    }, [fromError]);

    const toErrorMessage = React.useMemo(() => {
        switch (toError) {
            case 'invalidDate': {
                return "Please input a valid date";
            }
        }
    }, [toError]);

    useEffect(() => {
        if(isReset){
            setValue('eventName', "" );
            setValue('description', "" );
            setValue('organization', "" );
            setSelectedSubDivisions([]);
            setSelectedDivisions([]);
            setSelectedRegion(null);
            setSelectedType(null);
            setFromDate(null);
            setToDate(null);
            setIsReset(false)
        }
    }, [isReset]);

    useEffect(()=>{
        if(divisionList.length >0 && subDivisionList.length >0){
            setRefEvent(refTemplateData);
        }
    },[divisionList,subDivisionList]);

    useEffect(() => {
        if (Object.keys(refEvent).length > 0
            && params.id > 0
        ) {
            setSelectedRegion(getComboValueByLabel(EVENT_REGION_COMBO,refEvent.selectedRegion));
            setSelectedDivisions(getComboValueByIdList(divisionList,refEvent.selectedDivisions));
            setSelectedType(getComboValueByLabel(EVENT_TYPE_COMBO,refEvent.selectedType));
            setSelectedSubDivisions(getComboValueByIdList(subDivisionList,refEvent.selectedSubDivisions));
            setFromDate(
                refEvent.fromDate === null ? null : dayjs(refEvent.fromDate)
            );
            setToDate(
                refEvent.toDate === null ? null : dayjs(refEvent.toDate)
            );
            setOnReady(true);
        }
        else if ( params.id < 0){
            setOnReady(true);
        }
    }, [refEvent]);

    useEffect(() => {
        if(isCollectData){
            if(!fromError && !toError){
                let data = {
                    selectedRegion: selectedRegion === null ? null : selectedRegion.label,
                    selectedType: selectedType === null ? null : selectedType.label,
                    selectedDivisions: selectedDivisions.length === 0 ? [] : getIdList(selectedDivisions),
                    selectedSubDivisions: selectedSubDivisions.length === 0 ? [] : getIdList(selectedSubDivisions),
                    fromDate: fromDate === null ? null : dayjs(fromDate).format('YYYY-MM-DD'),
                    toDate: toDate === null ? null : dayjs(toDate).format('YYYY-MM-DD'),
                };
                applyTemplateValue(data);
            }
            else{
                setIsCollectData(false);
            }
        }
    }, [isCollectData]);

    // useEffect(() => {
    //     if(selectedDivisions !== null && selectedDivisions !== undefined){
    //         //change according to subDivision
    //         const temp = selectedDivisions.length > 0 ? getIdList(selectedDivisions) : [];
    //         getSubDivisionCombo(temp);
    //     }
    //     if(selectedDivisions.length <=0){
    //         setSelectedSubDivisions([]);
    //     }
    // }, [selectedDivisions]);

    // useEffect(() => {
    //     if(selectedDivisions.length >0){
    //         removeInvalidSubDivision(getIdList(selectedDivisions));
    //     }
    // }, [subDivisionList]);
    //
    // function removeInvalidSubDivision (divisionIdList){
    //     let temp = selectedSubDivisions;
    //     let output = [];
    //     for(let i=0 ; i<temp.length; i++){
    //         for(let j=0 ; j<temp.length; j++){
    //             if(temp[i].divisionId === divisionIdList[j]){
    //                 output.push(temp[i]);
    //             }
    //         }
    //     }
    //     setSelectedSubDivisions(
    //         getComboValueByIdList(
    //             subDivisionList,
    //             getIdList(output),
    //         ));
    // }

    function getSubDivisionCombo(divisionIds){
        axios.get(`${apiPath}${GET_SUB_DIVISION_COMBO_LIST}`,
            {
                params: {
                    "divisionIds": divisionIds
                },
                paramsSerializer: function (params) {
                    return Qs.stringify(params, { arrayFormat: 'repeat' });
                },
            })
            .then((response) => {
                if (response.status === 200) {
                    setSubDivisionList(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function getDivisionCombo(){
        axios.get(`${apiPath}${GET_DIVISION_COMBO_LIST}`)
            .then((response) => {
                if (response.status === 200) {
                    setDivisionList(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    useEffect(() => {
        getDivisionCombo();
        getSubDivisionCombo(null);
    }, []);

    return !onReady ?
        <LoadingComponent/>
        :
    <Grid container>
        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
            <Grid container >
                <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                    <Typography variant="lionerSize" component="span">
                    Event Name:
                    </Typography>
                </Grid>

                <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                    <TextField
                        fullWidth
                        inputProps={{maxLength: 255}}
                        {...register("eventName",{
                            value:  refEvent === null ? null : refEvent.eventName,
                        })}
                        id='eventName'
                        autoComplete="off"
                    />
                </Grid>
            </Grid>
        </Grid>

        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
            <Grid container >
                <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                    <Typography variant="lionerSize" component="span">
                    Event Description:
                    </Typography>
                </Grid>

                <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                    <TextField
                        fullWidth
                        inputProps={{maxLength: 500}}
                        {...register("description",{
                            value:  refEvent === null ? null : refEvent.description,
                        })}
                        id="description"
                        autoComplete="off"
                    />
                </Grid>
            </Grid>
        </Grid>

        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
            <Grid container >
                <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                    <Typography variant="lionerSize" component="span">
                        Event Organization:
                    </Typography>
                </Grid>

                <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                    <TextField
                        fullWidth
                        inputProps={{maxLength: 255}}
                        {...register("organization",{
                            value: refEvent === null ? null : refEvent.organization,
                        })}
                        id="organization"
                        autoComplete="off"
                    />
                </Grid>
            </Grid>
        </Grid>

        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
            <Grid container >
                <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                    <Typography variant="lionerSize" component="span">
                        Event Region:
                    </Typography>
                </Grid>

                <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                    <Autocomplete
                        disablePortal
                        id="region-combo"
                        size="small"
                        value={selectedRegion === null? null : selectedRegion}
                        options={EVENT_REGION_COMBO}
                        onChange={(event, newValue) => {
                            setSelectedRegion(newValue);
                        }}
                        isOptionEqualToValue={isOptionEqualToValue}
                        renderInput={(params) => <TextField {...params} />}
                    />
                </Grid>
            </Grid>
        </Grid>

        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
            <Grid container >
                <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                    <Typography variant="lionerSize" component="span">
                        Event Type:
                    </Typography>
                </Grid>

                <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                    <Autocomplete
                        disablePortal
                        id="event-type-combo"
                        size="small"
                        value={selectedType === null? null : selectedType}
                        options={EVENT_TYPE_COMBO}
                        onChange={(event, newValue) => {
                            setSelectedType(newValue);
                        }}
                        isOptionEqualToValue={isOptionEqualToValue}
                        renderInput={(params) => <TextField {...params} />}
                    />
                </Grid>
            </Grid>
        </Grid>

        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
            <Grid container >
                <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                    <Typography variant="lionerSize" component="span">
                        Application Date:
                    </Typography>
                </Grid>

                <Grid item xs={12} s={6} md={5} lg={6}>
                    <Grid container>
                        <Grid item xs={5.25} s={5.25} md={5.25} lg={5.5}>
                            <LocalizationProvider dateAdapter={AdapterDayjs}>
                                <DemoItem  components={['DatePicker']}>
                                    <DatePicker
                                        id="fromDate"
                                        format="DD/MM/YYYY"
                                        onError={(newError) => setFromError(newError)}
                                        slotProps={{
                                            field: { clearable: true },
                                            textField: {
                                                helperText: fromErrorMessage,
                                            },
                                        }}
                                        value={fromDate === null ? null : dayjs(fromDate)}
                                        onChange={(newValue) => setFromDate(newValue)}
                                    />
                                </DemoItem >
                            </LocalizationProvider>
                        </Grid>

                        <Grid item xs={1.5} s={1.5} md={1.5} lg={1} sx={{mt:1.3,display: 'flex', justifyContent:"center", alignItems: 'flex-start'}}>
                            <Typography variant="lionerSize" component="span">
                                To
                            </Typography>
                        </Grid>

                        <Grid item xs={5.25} s={5.25} md={5.25} lg={5.5}>
                            <LocalizationProvider dateAdapter={AdapterDayjs}>
                                <DemoItem  components={['DatePicker']}>
                                    <DatePicker
                                        id="toDate"
                                        format="DD/MM/YYYY"
                                        onError={(newError) => setToError(newError)}
                                        slotProps={{
                                            field: { clearable: true },
                                            textField: {
                                                helperText: toErrorMessage,
                                            },
                                        }}
                                        value={toDate === null ? null : dayjs(toDate)}
                                        onChange={(newValue) => setToDate(newValue)}
                                    />
                                </DemoItem >
                            </LocalizationProvider>
                        </Grid>
                    </Grid>
                </Grid>
            </Grid>
        </Grid>

        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
            <Grid container >
                <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                    <Typography variant="lionerSize" component="span">
                        Division:
                    </Typography>
                </Grid>

                <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                    <Autocomplete
                        multiple
                        disablePortal
                        id="division-combo"
                        size="small"
                        value={selectedDivisions === null? null : selectedDivisions}
                        options={divisionList}
                        onChange={(event, newValue) => {
                            setSelectedDivisions(newValue);
                        }}
                        isOptionEqualToValue={isOptionEqualToValue}
                        renderInput={(params) => <TextField {...params} />}
                    />
                </Grid>
            </Grid>
        </Grid>

        <Grid item xs={12} s={12} md={12} lg={12} sx={{ml:3, mr:3, mb:3}}>
            <Grid container >
                <Grid item xs={12} s={12} md={12} lg={2} sx={{display: 'flex', alignItems: 'center'}}>
                    <Typography variant="lionerSize" component="span">
                        Sub-Division:
                    </Typography>
                </Grid>

                <Grid item xs={12} s={12} md={12} lg={6} justifyContent="space-between" alignItems="right">
                    <Autocomplete
                        multiple
                        disablePortal
                        id="sub-division-combo"
                        size="small"
                        value={selectedSubDivisions === null? null : selectedSubDivisions}
                        options={subDivisionList}
                        //disabled={selectedDivisions.length<=0}
                        onChange={(event, newValue) => {
                            setSelectedSubDivisions(newValue);
                        }}
                        isOptionEqualToValue={isOptionEqualToValue}
                        renderInput={(params) => <TextField {...params} />}
                    />
                </Grid>
            </Grid>
        </Grid>
    </Grid>

}