// material-ui
import {
    Button,
    Typography,
    Grid, TextField, InputLabel, CardActions
} from '@mui/material';
import MainCard from "../../../components/MainCard";
import {useForm} from "react-hook-form";
import {useContext, useState} from "react";
// import {useContext, useEffect, useState} from "react";
import Autocomplete from '@mui/material/Autocomplete';
import * as React from "react";
// import axios from "axios";
import {apiPath, getUserData} from "../../../auth/utils";
// import {
//     GET_CONSULTANT_COMBO_LIST, GET_EVENT_EXPORT,
//     GET_SUB_CONSULTANT_COMBO_LIST, POST_SEARCH_TEMPLATE_PATH, VALIDATE_TEMPLATE_NAME_PATH,
// } from "../../../utils/ApiPathConst";
import {LIONER_BUTTON_THEME} from "../../../themes/colorConst";
// import {
//     GeneralCreateTemplateWindow,
//     getComboValueByIdList, getComboValueByLabel,
//     getIdList, isOptionEqualToValue, notifySaveSuccess,
// } from "../../../utils/CommonFunction";
// import Qs from 'qs';
import {useNavigate} from "react-router";
import {ThemeProvider} from "@emotion/react";
// import UploadContext from "../../../components/UploadProvider";
// 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 {isObjEmpty} from "../../../utils/Utils";
// import {useLocation} from "react-router-dom";
import AbilityContext from "../../../components/AbilityProvider";
import {LIONER_FORM_THEME, CARD_MAX_WIDTH} from "../../../themes/themeConst";
import Collapse from '@mui/material/Collapse';
import {ExpandMore} from "@mui/icons-material";
import ExpandMoreIcon from '@mui/icons-material/ExpandMore';
import { isNull } from 'lodash';

// ==============================|| DASHBOARD - DEFAULT ||============================== //

// const EventSearchForm = ({applySearch, refTemplateData, isUpdating,
//                              setIsUpdating, getTemplateList,setExpanded,expanded,userConsultant}) => {
const ClientSearchForm = ({applySearch, setExpanded,expanded}) => {

    const navigate = useNavigate()
    // const location = useLocation();
    // const queryParams = new URLSearchParams(location.search);
    // const { setIsUploading } = useContext(UploadContext);
    const ability = useContext(AbilityContext);


    // const [selectedRegion, setSelectedRegion] = useState(null);
    // const [selectedType, setSelectedType] = useState(null);
    // const [selectedCaseManager, setSelectedCaseManager] = useState([]);
    // const [selectedConsultants, setSelectedConsultants] = useState([]);
    const [createDateFrom, setCreateDateFrom] = useState(null);
    const [createDateTo, setCreateDateTo] = useState(null);

    // const [caseManagerList, setCaseManagerList] = useState([]);
    // const [consultantList, setConsultantList] = useState([]);

    const { setValue, reset, register, handleSubmit, getValues } = useForm()
    const handleExpandClick = () => {
        setExpanded(!expanded);
    };

    const [createDateFromError, setCreateDateFromError] = React.useState(null);
    const [createDateToError, setCreateDateToError] = React.useState(null);

    const createDateFromErrorMessage = React.useMemo(() => {
        switch (createDateFromError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [createDateFromError]);

    const createDateToErrorMessage = React.useMemo(() => {
        switch (createDateToError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [createDateToError]);

    const createNewClient = () => {
        navigate(`/client/maintain/-1`);
    };

    const onSubmit = (data) => {
        const criteria = {
            ...data,
            createDateFrom: createDateFrom === null ? null : dayjs(createDateFrom).format('YYYY-MM-DD'),
            createDateTo: createDateTo === null ? null : dayjs(createDateTo).format('YYYY-MM-DD'),
            // region: selectedRegion === null ? null : selectedRegion.label,
            // type: selectedType === null ? null :selectedType.label,
            // consultantIdList: getIdList(selectedConsultants),
            // caseManagerIdList: getIdList(selectedCaseManager),
        };
        applySearch(criteria);
    };

    // function onExport(){
    //     const data = getValues();
    //     const temp = {
    //         ...data,
    //         fromDate: fromDate === null ? null : dayjs(fromDate).format('YYYY-MM-DD'),
    //         createDateTo: createDateTo === null ? null : dayjs(createDateTo).format('YYYY-MM-DD'),
    //         region: selectedRegion === null ? null : selectedRegion.label,
    //         type: selectedType === null ? null :selectedType.label,
    //         consultantIdList: getIdList(selectedConsultants),
    //         caseManagerIdList: getIdList(selectedCaseManager),
    //     };
    //     setIsUploading(true);
    //     axios.get(`${apiPath}${GET_EVENT_EXPORT}`,{
    //         responseType: 'blob',
    //         params: temp,
    //         paramsSerializer: function (params) {
    //             return Qs.stringify(params, { arrayFormat: 'repeat' });
    //         },
    //     })
    //         .then((response) => {
    //             if (response.status === 200) {
    //                 setIsUploading(false);
    //                 const url = URL.createObjectURL(new Blob([response.data]));
    //                 const link = document.createElement("a");
    //                 link.href = url;
    //                 link.setAttribute("download", "event_export_"+ Date.now() + ".xlsx");
    //                 link.click();
    //             }
    //         })
    //         .catch(error => {
    //             setIsUploading(false);
    //             console.log(error);
    //             return false;
    //         });
    // }

    // function getCaseManagerCombo(caseManagerIds){
    //     axios.get(`${apiPath}${GET_CASE_MANAGER_COMBO_LIST}`,
    //         {
    //             params: {
    //                 "caseManagerIds": caseManagerIds
    //             },
    //             paramsSerializer: function (params) {
    //                 return Qs.stringify(params, { arrayFormat: 'repeat' });
    //             },
    //         })
    //         .then((response) => {
    //             if (response.status === 200) {
    //                 setCaseManagerList(response.data.records);
    //                 if(!isObjEmpty(refEvent) && isUpdating){
    //                     setSelectedCaseManager(getComboValueByIdList(response.data.records,refEvent.selectedCaseManager));
    //                     setIsUpdating(false);
    //                 }
    //             }
    //         })
    //         .catch(error => {
    //             console.log(error);
    //             return false;
    //         });
    // }

    // function getConsultantCombo(){
    //     axios.get(`${apiPath}${GET_CONSULTANT_COMBO_LIST}`)
    //         .then((response) => {
    //             if (response.status === 200) {
    //                 setConsultantList(response.data.records);
    //             }
    //         })
    //         .catch(error => {
    //             console.log(error);
    //             return false;
    //         });
    // }

    // useEffect(() => {
    //     getConsultantCombo();
    //     getCaseManagerCombo(null);
    //     const year = queryParams.get('year');
    //     if(year !== null){
    //         setFromDate(
    //             dayjs(year+"-01-01 00:00:00")
    //         );
    //         setToDate(
    //             dayjs(year+"12-31")
    //         );
    //     }
    // }, []);

    // useEffect(() => {
    //     const userCaseManager = queryParams.get('userCaseManager');
    //     if(userCaseManager === "true" &&
    //         !isObjEmpty(userConsultant) &&
    //         !isObjEmpty(consultantList)){
    //         setSelectedConsultants(getComboValueByIdList(consultantList,[userConsultant.id]));
    //     }
    // }, [userConsultant,consultantList]);

    function resetForm(){
        setCreateDateFrom(null);
        setCreateDateTo(null);
        // setToDate(null);
        reset();
    }

    return (
        <MainCard xs={12} md={12} lg={12}
                  content={false}
                  sx={{width:CARD_MAX_WIDTH}}
        >
            <Grid item onClick={handleExpandClick}>
            <CardActions disableSpacing>
                {/*row 1*/}
                <Grid item justifyContent="space-between" alignItems="center" sx={{mt:1,ml:2,mb:1}}>
                    <Typography variant="lionerSubLabel" >
                        Search Criteria(s)
                    </Typography>
                </Grid>

                <ExpandMore
                    expand={expanded.toString()}
                    onClick={handleExpandClick}
                    aria-expanded={expanded}
                    aria-label="show more"
                    style={{ marginLeft: 'auto' }} // Align the button to the right
                >
                    <ExpandMoreIcon />
                </ExpandMore>
            </CardActions>
            </Grid>

            <Collapse in={expanded} timeout="auto" unmountOnExit>
                <form onSubmit={handleSubmit(onSubmit)}>
                <ThemeProvider theme={LIONER_FORM_THEME}>
                {/*row 2*/}
                <Grid container alignItems={"flex-start"} >
                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="clientCode">Client Code</InputLabel>
                        <TextField
                            fullWidth
                            {...register("clientCode")}
                            inputProps={{maxLength: 500}}
                            id="clientCode"
                            autoComplete="off"
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="clientLastName">Client Last Name</InputLabel>
                        <TextField
                            fullWidth
                            {...register("lastname")}
                            inputProps={{maxLength: 500}}
                            id="lastname"
                            autoComplete="off"
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="clientFirstName">Client First Name</InputLabel>
                        <TextField
                            fullWidth
                            {...register("firstname")}
                            inputProps={{maxLength: 500}}
                            id="firstname"
                            autoComplete="off"
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="phone1">Phone No.</InputLabel>
                        <TextField
                            fullWidth
                            inputProps={{maxLength: 255}}
                            {...register("phone1")}
                            id="phone1"
                            autoComplete="off"
                        />
                    </Grid>

                    {/* <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="eventName">Case Manager</InputLabel>
                        <Autocomplete
                        multiple
                            disablePortal
                            id="case-manager-combo"
                            size="small"
                            value={selectedCaseManager === null? null : selectedCaseManager}
                            options={caseManagerList}
                            //disabled={selectedConsultants.length<=0}
                            onChange={(event, newValue) => {
                                setSelectedCaseManager(newValue);
                            }}
                            renderInput={(params) => <TextField {...params} />}
                            isOptionEqualToValue={isOptionEqualToValue}
                        />
                    </Grid>
                    
                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="eventName">Consultant</InputLabel>
                            <Autocomplete
                                multiple
                                disablePortal
                                id="consultant-combo"
                                size="small"
                                value={selectedConsultants === null? null : selectedConsultants}
                                options={consultantList}
                                onChange={(event, newValue) => {
                                    setSelectedConsultants(newValue);
                                    }}
                                    renderInput={(params) => <TextField {...params} />}
                                    isOptionEqualToValue={isOptionEqualToValue}
                            />
                    </Grid> */}

                    {/* <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="caseManager">Case Manager</InputLabel>
                        <Autocomplete
                            disablePortal
                            id="region-combo"
                            size="small"
                            value={selectedRegion === null? null : selectedRegion}
                            options={EVENT_REGION_COMBO}
                            onChange={(event, newValue) => {
                                setSelectedRegion(newValue);
                            }}
                            renderInput={(params) => <TextField {...params}/>}
                            isOptionEqualToValue={isOptionEqualToValue}
                        />
                    </Grid>
                    
                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="consultant">Consultant</InputLabel>
                        <Autocomplete
                            disablePortal
                            id="event-type-combo"
                            size="small"
                            value={selectedType === null? null : selectedType}
                            options={EVENT_TYPE_COMBO}
                            onChange={(event, newValue) => {
                                setSelectedType(newValue);
                            }}
                            renderInput={(params) => <TextField {...params} />}
                            isOptionEqualToValue={isOptionEqualToValue}
                        />
                    </Grid> */}

                    {/* <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="createDateFrom">Create Date</InputLabel>

                        <Grid container>
                            <Grid item xs={5.25} s={5.25} md={5.25} lg={5.5}>
                                <LocalizationProvider dateAdapter={AdapterDayjs}>
                                    <DemoItem>
                                        <DatePicker
                                            id="createDateFrom"
                                            onError={(newError) => setCreateDateFromError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: createDateFromErrorMessage,
                                                },
                                            }}
                                            format="DD/MM/YYYY"
                                            value={createDateFrom === null ? null : dayjs(createDateFrom)}
                                            onChange={(newValue) => setCreateDateFrom(newValue)}
                                            // label="From"
                                        />
                                    </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'}}>
                            To
                            </Grid>

                            <Grid item xs={5.25} s={5.25} md={5.25} lg={5.5}>
                                <LocalizationProvider dateAdapter={AdapterDayjs}>
                                    <DemoItem  components={['DatePicker']}>
                                        <DatePicker
                                            format="DD/MM/YYYY"
                                            onError={(newError) => setCreateDateToError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    helperText: createDateToErrorMessage,
                                                },
                                            }}
                                            id="createDateTo"
                                            //label="To Date"
                                            value={createDateTo === null ? null : dayjs(createDateTo)}
                                            onChange={(newValue) => setCreateDateTo(newValue)}
                                        />
                                    </DemoItem >
                                </LocalizationProvider>
                            </Grid>
                        </Grid>
                    </Grid> */}

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5}}>
                        <InputLabel htmlFor="remarks">Remarks</InputLabel>
                        <TextField
                            fullWidth
                            {...register("remarks")}
                            inputProps={{maxLength: 500}}
                            id="remarks"
                            autoComplete="off"
                        />
                    </Grid>

                </Grid>


                {/*last row*/}
                <Grid container maxWidth justifyContent="space-between" sx={{mt:1.5}}>
                    <ThemeProvider theme={LIONER_BUTTON_THEME}>
                    <Grid item>
                        <Grid container>
                            <Grid item sx={{ml:3, mr:1.5, mb:2}}>
                                <Button
                                    variant="contained"
                                    type="submit"
                                    color="save"
                                    disabled={createDateFromError || createDateToError}
                                >
                                    Search
                                </Button>
                            </Grid>

                            {/* <Grid item sx={{ml:1.5, mr:1.5, mb:2}}>
                                <Button
                                    variant="contained"
                                    color="export"
                                    // onClick={onExport}
                                    // disabled={createDateFromError || createDateToError}
                                >
                                    Export
                                </Button>
                            </Grid> */}

                            <Grid item sx={{ml:{xs:1.5, md:1.5, lg:1.5}, mr:1.5, mb:2}}>
                                <Button
                                    variant="contained"
                                    color="cancel"
                                    onClick={resetForm}
                                    >
                                    Reset
                                </Button>
                            </Grid>
                        </Grid>
                    </Grid>

                    <Grid item>
                        <Grid container>
                            {ability.can('MAINTAIN','CLIENT') ?
                                <Grid item sx={{ml:3, mr:3, mb:0.5}}>
                                    <Button
                                        variant="contained"
                                        color="create"
                                        onClick={createNewClient}
                                        >
                                        New Client
                                    </Button>
                                </Grid>
                                :
                                <Grid/>
                            }
                        </Grid>
                    </Grid>
                    </ThemeProvider>
                </Grid>
                </ThemeProvider>
                </form>
            </Collapse>
        </MainCard>
    );
};

export default ClientSearchForm;
