// material-ui
import {
    Button,
    CardContent,
    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";
import {FormattedMessage, useIntl} from "react-intl";
// ==============================|| DASHBOARD - DEFAULT ||============================== //


const SearchPublicNoticeForm = ({ applySearch, searchCriteria, issueComboData
}) => {
    const intl = useIntl();
    const [type, setType] = React.useState([]);
    const [status, setStatus] = React.useState(ComboData.proofStatus[0]);
    const [issueSelected, setIssueSelected] = React.useState({});
    const [issueCombo, setIssueCombo] = React.useState([]);
    const [groupSelected, setGroupSelected] = React.useState({});

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

    const _sx = {
        padding: "4 2 4 2",
        boxShadow: 1,
        border: 1,
        borderColor: '#DDD',
        '& .MuiDataGrid-cell': {
            borderTop: 1,
            borderBottom: 1,
            borderColor: "#EEE"
        },
        '& .MuiDataGrid-footerContainer': {
            border: 1,
            borderColor: "#EEE"
        }
    }

    const { reset, register, handleSubmit } = useForm()
    const onSubmit = (data) => {

        let typeArray = [];

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

        const temp = {
            refNo: data.refNo,
            code: data.code,
            issueId: issueSelected?.id,
            gazettGroup: groupSelected?.type,
            dateFrom: data.dateFrom,
            dateTo: data.dateTo,
            //contact: data.contact,
            replyed: (status?.type && status?.type != 'all') ? status?.type : "",
        };
        applySearch(temp);
    };


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

    function resetForm() {
        setType([]);
        setStatus(ComboData.proofStatus[0]);
        setIssueSelected({});
        setGroupSelected({});
        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={_sx}
        >

            <form onSubmit={handleSubmit(onSubmit)}>
                {/*row 1*/}
                <CardContent sx={{ px: 2.5, pt: 3 }}>
                    <Grid item justifyContent="space-between" alignItems="center">
                        <Typography variant="pnspsFormHeader">
                            <FormattedMessage id="searchForm"/>
                        </Typography>
                    </Grid>
                </CardContent>

                {/*row 2*/}
                <Grid container alignItems={"center"}>
                    <Grid item xs={12} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                        <TextField
                            fullWidth
                            {...register("refNo")}
                            id='refNo'
                            label={intl.formatMessage({id: 'proofId'}) + ":"}
                            defaultValue={searchCriteria.refNo}
                            InputLabelProps={{
                                shrink: true
                            }}
                        />
                    </Grid>

                    <Grid item xs={12} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                        <TextField
                            fullWidth
                            {...register("code")}
                            id='code'
                            label={intl.formatMessage({id: 'applicationId'}) + ":"}
                            defaultValue={searchCriteria.code}
                            InputLabelProps={{
                                shrink: true
                            }}
                        />
                    </Grid>

                    <Grid item xs={12} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                        <Autocomplete
                            {...register("issueId")}
                            disablePortal
                            id="issueId"
                            options={issueCombo}
                            value={issueSelected}
                            inputValue={(issueSelected?.id) ? getIssueLabel(issueSelected) : ""}
                            getOptionLabel={(option) => getIssueLabel(option)}
                            onChange={(event, newValue) => {
                                setIssueSelected(newValue);
                            }}
                            renderInput={(params) => (
                                <TextField {...params}
                                    label={intl.formatMessage({id: 'gazetteCount'})}
                                    InputLabelProps={{
                                        shrink: true
                                    }}
                                />
                            )}
                        />
                    </Grid>

                    {/* <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                        <Autocomplete
                            {...register("gazettGroup")}
                            disablePortal
                            id="gazettGroup"
                            options={ComboData.groupTitle}
                            value={groupSelected}
                            inputValue={(groupSelected?.labelCht) ? groupSelected?.labelCht : ""}
                            getOptionLabel={(option) => option.labelCht}
                            onChange={(event, newValue) => {
                                setGroupSelected(newValue);
                            }}
                            renderInput={(params) => (
                                <TextField {...params}
                                    label="憲報類型"
                                    InputLabelProps={{
                                        shrink: true
                                    }}
                                />
                            )}
                        />
                    </Grid> */}

                    <Grid item xs={12} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                        <Grid container>
                            <Grid item xs={5.25} s={5.25} md={5.25} lg={5.5}>
                                <TextField
                                    fullWidth
                                    {...register("dateFrom")}
                                    id="dateFrom"
                                    type="date"
                                    label={intl.formatMessage({id: 'proofDateFrom'})}
                                    defaultValue={searchCriteria.dateFrom}
                                    InputProps={{ inputProps: { max: maxDate } }}
                                    onChange={(newValue) => {
                                        setMinDate(DateUtils.dateStr(newValue));
                                    }}
                                    InputLabelProps={{
                                        shrink: true
                                    }}
                                />
                            </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'}}>
                                <FormattedMessage id="to" />
                            </Grid>

                            <Grid item xs={5.25} s={5.25} md={5.25} lg={5.5}>
                                <TextField
                                    fullWidth
                                    InputLabelProps={{
                                        shrink: true
                                    }}
                                    {...register("dateTo")}
                                    InputProps={{ inputProps: { min: minDate } }}
                                    onChange={(newValue) => {
                                        setMaxDate(DateUtils.dateStr(newValue));
                                    }}
                                    id="dateTo"
                                    type="date"
                                    //label="校對日期(到)"
                                    defaultValue={searchCriteria.dateTo}
                                />
                            </Grid>
                        </Grid>
                    </Grid>

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

                    </Grid> */}

                    <Grid item xs={12} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                        <Autocomplete
                            {...register("status")}
                            disablePortal={false}
                            size="small"
                            id="status"
                            filterOptions={(options) => options}
                            options={ComboData.proofStatus}
                            value={status}
                            getOptionLabel={(option) => option.type? intl.formatMessage({ id: option.i18nLabel }) : ""}
                            inputValue={status? intl.formatMessage({ id: status.i18nLabel }) : ""}
                            onChange={(event, newValue) => {
                                if (newValue !== null) {
                                    setStatus(newValue);
                                }
                            }}
                            renderInput={(params) => (
                                <TextField {...params}
                                    label={intl.formatMessage({id: 'status'})}
                                />
                            )}
                            InputLabelProps={{
                                shrink: true
                            }}
                        />
                    </Grid>

                </Grid>


                {/*last row*/}
                <Grid container maxWidth justifyContent="flex-end">
                    <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                    <Grid item sx={{ mr: 3, mb: 3 }}>
                        <Button
                            variant="contained"
                            color="cancel"
                            onClick={resetForm}
                            aria-label={intl.formatMessage({id: 'reset'})}
                        >
                            <FormattedMessage id="reset"/>
                        </Button>
                    </Grid>

                    <Grid item sx={{mr: 3, mb: 3 }}>
                        <Button
                            variant="contained"
                            type="submit"
                            aria-label={intl.formatMessage({id: 'submit'})}
                        >
                            <FormattedMessage id="submit"/>
                        </Button>
                    </Grid>
                    </ThemeProvider>
                </Grid>
            </form>
        </MainCard>
    );
};

export default SearchPublicNoticeForm;
