// 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 {
    isORGLoggedIn,
  } from "utils/Utils";
import {PNSPS_BUTTON_THEME} from "../../../themes/buttonConst";
import {ThemeProvider} from "@emotion/react";
import {FormattedMessage, useIntl} from "react-intl";
// ==============================|| DASHBOARD - DEFAULT ||============================== //


const SearchPublicNoticeForm = ({ applySearch, searchCriteria }) => {
    const intl = useIntl();
    const [type, setType] = React.useState([]);
    const [status, setStatus] = React.useState([{ key: 0, label: 'all', type: 'all' }]);

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

    const { reset, register, handleSubmit } = useForm()
    const marginBottom = 2.5;

    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,
            dateFrom: data.dateFrom,
            dateTo: data.dateTo,
            contact: data.contact,
            careOf: data.careOf?data.careOf:"",
            status: (data.status === "" || data.status.includes('all')) ? "" : data.status,
        };
        applySearch(temp);
    };

    function resetForm() {
        setType([]);
        setStatus([{ key: 0, label: 'All', labelCht: "全部", type: 'all' }]);
        reset();
    }

    return (
        <MainCard xs={12} md={12} lg={12}
            border={false}
            content={false}>

            <form onSubmit={handleSubmit(onSubmit)}>
                {/*row 1*/}
                <Grid item justifyContent="space-between" alignItems="center" sx={{mt:1,ml:3,mb:marginBottom}}>
                    <Typography variant="pnspsFormHeader" >
                        <FormattedMessage id="searchForm"/>
                    </Typography>
                </Grid>
                {/*row 2*/}
                <Grid container alignItems={"center"}>
                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                        <TextField
                            fullWidth
                            {...register("appNo")}
                            id='appNo'
                            aria-label={intl.formatMessage({id: 'applicationId'})}
                            label={intl.formatMessage({id: 'applicationId'})}
                            defaultValue={searchCriteria.appNo}
                            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"
                            aria-label={intl.formatMessage({id: 'submitDateFrom'})}
                            label={intl.formatMessage({id: 'submitDateFrom'})}
                            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")}
                            id="dateTo"
                            type="date"
                            aria-label={intl.formatMessage({id: 'submitDateTo'})}
                            label={intl.formatMessage({id: 'submitDateTo'})}
                            defaultValue={searchCriteria.dateTo}
                            InputProps={{ inputProps: { min: minDate } }}
                            onChange={(newValue) => {
                                setMaxDate(DateUtils.dateStr(newValue));
                            }}
                        />
                    </Grid>
                    {isORGLoggedIn()?
                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                            <TextField
                                fullWidth
                                {...register("careOf")}
                                id="careOf"
                                label="Care Of"
                                aria-label={"Care Of"}
                                defaultValue={searchCriteria.careOf}
                                InputLabelProps={{
                                    shrink: true
                                }}
                            />
                        </Grid>:null                    
                    }

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

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                        <Autocomplete
                            multiple
                            {...register("status")}
                            id="status"
                            size="small"
                            // filterOptions={(options)=>options}
                            options={
                                localStorage.getItem('userData').creditor ?
                                    ComboData.publicNoticeStatic_Creditor :
                                    ComboData.publicNoticeStatic
                            }
                            value={status}
                            // inputValue={status?.labelCht}
                            getOptionLabel={(option) => intl.formatMessage({id: option.label})}
                            onChange={(event, newValue) => {
                                console.log(newValue)
                                const findAllIndex = newValue.findIndex((ele) => {
                                    return ele.type === "all"
                                })

                                if (findAllIndex > -1) {
                                    setStatus([newValue[findAllIndex]]);
                                    setSelectedLabelsString('all')
                                } else {
                                    const selectedLabels = newValue.map(option => option.type);
                                    const selectedLabelsString = `${selectedLabels.join(',')}`;
                                    setStatus(newValue);
                                    console.log(newValue)
                                    setSelectedLabelsString(selectedLabelsString);
                                }
                                console.log(selectedLabelsString)
                                console.log(status)
                            }}
                            renderInput={(params) => (
                                <TextField {...params}
                                    label={intl.formatMessage({id: 'status'})}
                                    aria-label={intl.formatMessage({id: 'status'})}
                                    InputLabelProps={{
                                        shrink: true
                                    }}
                                />
                            )}
                        // InputLabelProps={{
                        //     shrink: true
                        // }}
                        />
                    </Grid>
                    {/*<Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:3}}>*/}
                    {/*    <TextField*/}
                    {/*        fullWidth*/}
                    {/*        {...register("subDivisionId")}*/}
                    {/*        id="subDivision"*/}
                    {/*        label="Sub-Division"*/}
                    {/*    />*/}
                    {/*</Grid>*/}

                </Grid>


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

                    <Grid item>
                        <Button
                            variant="contained"
                            type="submit"
                            aria-label={intl.formatMessage({id: 'search'})}
                        >
                            <Typography variant="pnspsButtonText">
                                <FormattedMessage id="search"/>
                            </Typography>
                        </Button>
                    </Grid>
                    </ThemeProvider>
                </Grid>
            </form>
        </MainCard>
    );
};

export default SearchPublicNoticeForm;
