// material-ui
import {
    Button,
    Grid, TextField,
    Autocomplete,
    Typography
} from '@mui/material';
import MainCard from "components/MainCard";
import { useForm } from "react-hook-form";
import * as React from "react";
import * as ComboData from "utils/ComboData";
import * as DateUtils from "utils/DateUtils";
import * as FormatUtils from "utils/FormatUtils";
import {PNSPS_BUTTON_THEME} from "../../../themes/buttonConst";
import {ThemeProvider} from "@emotion/react";
// ==============================|| DASHBOARD - DEFAULT ||============================== //


const SearchDemandNoteForm = ({ applySearch, orgComboData, searchCriteria, issueComboData
}) => {

    const [type, setType] = React.useState([]);
    // const [status, setStatus] = React.useState({ key: 0, label: 'All', type: 'all' });
    const [orgSelected, setOrgSelected] = React.useState({});
    const [orgCombo, setOrgCombo] = React.useState();
    const [issueSelected, setIssueSelected] = React.useState({});
    const [issueCombo, setIssueCombo] = React.useState([]);
    const [selectedStatus, setSelectedStatus] = React.useState([]);
    const [selectedLabelsString, setSelectedLabelsString] = React.useState('');

    const [minDate, setMinDate] = React.useState(searchCriteria.dateFrom);
    const [maxDate, setMaxDate] = React.useState(searchCriteria.dateTo);

    const { reset, register, handleSubmit } = useForm()
    const onSubmit = (data) => {
        data.status = selectedLabelsString
        let typeArray = [];

        for (let i = 0; i < type.length; i++) {
            typeArray.push(type[i].label);
        }

        const temp = {
            appNo: data.appNo,
            issueId: issueSelected?.id,
            orgId: (orgSelected?.key && orgSelected?.key > 0) ? orgSelected?.key : "",
            dnNo: data.dnNo,
            dateFrom: data.dateFrom,
            dateTo: data.dateTo,
            status: (data.status === '' || data.status.includes("all")) ? "" : data.status,
        };
        applySearch(temp);
    };


    React.useEffect(() => {
        if (orgComboData && orgComboData.length > 0) {
            setOrgCombo(orgComboData);
        }
    }, [orgComboData]);

    React.useEffect(() => {
        if (issueComboData && issueComboData.length > 0) {
            setIssueCombo(issueComboData);
        }
    }, [issueComboData]);

    function resetForm() {
        setType([]);
        // setStatus({ key: 0, label: 'All', type: 'all' });
        setOrgSelected({});
        setIssueSelected({});
        reset();
    }

    function getIssueLabel(data) {
        if (data == {}) return "";
        return data.year
            + " Vol. " + FormatUtils.zeroPad(data.volume, 3)
            + ", No. " + FormatUtils.zeroPad(data.issueNo, 2)
            + ", " + DateUtils.dateFormat(data.issueDate, "D MMM YYYY (ddd)");
    }

    return (
        <MainCard xs={12} md={12} lg={12}
            border={false}
            content={false}
            sx={{ backgroundColor: '#fff' }}
        >

            <form onSubmit={handleSubmit(onSubmit)}>
                <Grid container sx={{ backgroundColor: '#ffffff', ml: 2, mt: 1 }} width="98%">
                    {/*row 1*/}
                    <Grid item justifyContent="space-between" alignItems="center" sx={{mt:1, ml:3,mb:2.5}}>
                        <Typography variant="pnspsFormHeader" >
                            Search
                        </Typography>
                    </Grid>
                    {/*row 2*/}
                    <Grid container display="flex" alignItems={"center"}>

                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                            <Autocomplete
                                {...register("issueId")}
                                disablePortal
                                id="issueId"
                                size="small"
                                options={issueCombo}
                                value={issueSelected}
                                inputValue={(issueSelected?.id) ? getIssueLabel(issueSelected) : ""}
                                getOptionLabel={(option) => getIssueLabel(option)}
                                onChange={(event, newValue) => {
                                    if (newValue !== null) {
                                        setIssueSelected(newValue);
                                    }
                                }}
                                renderInput={(params) => (
                                    <TextField {...params}
                                        label="Gazette Issue"
                                        InputLabelProps={{
                                            shrink: true
                                        }}
                                    />
                                )}
                            />
                        </Grid>

                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                            <TextField
                                fullWidth
                                {...register("appNo")}
                                id='appNo'
                                label={"App No."}
                                defaultValue={searchCriteria.appNo}
                                InputLabelProps={{
                                    shrink: true
                                }}
                            />
                        </Grid>

                        {
                            orgCombo ?
                                <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                                    <Autocomplete
                                        {...register("orgId")}
                                        disablePortal
                                        id="orgId"
                                        size="small"
                                        options={orgCombo}
                                        value={orgSelected}
                                        inputValue={(orgSelected?.label) ? orgSelected?.label : ""}
                                        onChange={(event, newValue) => {
                                            if (newValue !== null) {
                                                setOrgSelected(newValue);
                                            }
                                        }}
                                        renderInput={(params) => (
                                            <TextField {...params}
                                                label="Organisation"
                                                InputLabelProps={{
                                                    shrink: true
                                                }}
                                            />
                                        )}
                                    />
                                </Grid>
                                : <></>
                        }


                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                            <TextField
                                fullWidth
                                {...register("dnNo")}
                                id='dnNo'
                                label="DN No."
                                defaultValue={searchCriteria.dnNo}
                                InputLabelProps={{
                                    shrink: true
                                }}
                            />
                        </Grid>

                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                            <TextField
                                fullWidth
                                {...register("dateFrom")}
                                id="dateFrom"
                                type="date"
                                label={"Issue Date(From)"}
                                defaultValue={searchCriteria.dateFrom}
                                InputProps={{ inputProps: { max: maxDate } }}
                                onChange={(newValue) => {
                                    setMinDate(DateUtils.dateStr(newValue));
                                }}
                                InputLabelProps={{
                                    shrink: true
                                }}
                            />
                        </Grid>

                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                            <TextField
                                fullWidth
                                InputLabelProps={{
                                    shrink: true
                                }}
                                {...register("dateTo")}
                                InputProps={{ inputProps: { min: minDate } }}
                                onChange={(newValue) => {
                                    setMaxDate(DateUtils.dateStr(newValue));
                                }}
                                id="dateTo"
                                type="date"
                                label={"Issue Date(To)"}
                                defaultValue={searchCriteria.dateTo}
                            />
                        </Grid>


                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                            <Autocomplete
                                multiple
                                size="small"
                                {...register("status")}
                                id="status"
                                options={ComboData.denmandNoteStatus}
                                value={selectedStatus}
                                onChange={(event, newValue) => {
                                    const findAllIndex = newValue.findIndex((ele) => {
                                        return ele.type === "all"
                                    })

                                    if (findAllIndex > -1) {
                                        setSelectedStatus([newValue[findAllIndex]]);
                                        setSelectedLabelsString('all')
                                    } else {
                                        const selectedLabels = newValue.map(option => option.type);
                                        const selectedLabelsString = `${selectedLabels.join(',')}`;
                                        setSelectedStatus(newValue);
                                        setSelectedLabelsString(selectedLabelsString);
                                    }
                                }}
                                getOptionLabel={(option) => option.label}
                                renderInput={(params) => (
                                    <TextField
                                        {...params}
                                        label="Status"
                                        InputLabelProps={{
                                            shrink: true
                                        }}
                                    />
                                )}
                            />
                        </Grid>



                    </Grid>

                    {/*last row*/}
                    <Grid container maxWidth justifyContent="flex-end">
                        <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                        <Grid item sx={{ ml: 3, mb:3 }}>
                            <Button
                                variant="contained"
                                onClick={resetForm}
                                >
                                Clear
                            </Button>
                        </Grid>

                        <Grid item sx={{ ml: 3, mr: 3, mb:3}}>
                            <Button
                                variant="contained"
                                type="submit"
                            >
                                Submit
                            </Button>
                        </Grid>
                        </ThemeProvider>
                    </Grid>
                </Grid>
            </form>
        </MainCard>
    );
};

export default SearchDemandNoteForm;
