// material-ui
import {
    Button,
    Grid, TextField,
    Autocomplete
} from '@mui/material';
import MainCard from "components/MainCard";
import OrgComboAutocomplete from "components/OrgComboAutocomplete";
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 { Typography } from '../../../../node_modules/@mui/material/index';
import {PNSPS_BUTTON_THEME} from "../../../themes/buttonConst";
import {ThemeProvider} from "@emotion/react";
import { useIntl } from "react-intl";

import {DatePicker} from "@mui/x-date-pickers/DatePicker";
import dayjs from "dayjs";
import {DemoItem} from "@mui/x-date-pickers/internals/demo";
import {LocalizationProvider} from "@mui/x-date-pickers/LocalizationProvider";
import {AdapterDayjs} from "@mui/x-date-pickers/AdapterDayjs";
// ==============================|| DASHBOARD - DEFAULT ||============================== //
const SearchPublicNoticeForm = ({ applySearch, searchCriteria, issueComboData, onGridReady
}) => {

    const [type, setType] = React.useState([]);
    const [status, setStatus] = React.useState(searchCriteria.statusKey!=undefined?ComboData.proofStatus_GLD[searchCriteria.statusKey]:ComboData.proofStatus_GLD[0]);
    const [orgSelected, setOrgSelected] = React.useState(null);
    const [issueSelected, setIssueSelected] = React.useState(null);
    const [issueCombo, setIssueCombo] = React.useState([]);
    const [groupSelected, setGroupSelected] = React.useState(
        searchCriteria.gazettGroup != undefined
            ? ComboData.groupTitle.find(item => item.title === searchCriteria.gazettGroup) ?? null
            : null
    );

    const [minDate, setMinDate] = React.useState(searchCriteria.dateFrom);
    const [maxDate, setMaxDate] = React.useState(searchCriteria.dateTo);
    const [fromDateValue, setFromDateValue] = React.useState("dd / mm / yyyy");
    const [toDateValue, setToDateValue] = React.useState("dd / mm / yyyy");

    // React.useEffect(() => {
    //     if(searchCriteria.status!=undefined){
    //         if(searchCriteria.status === ""){
    //             ComboData.proofStatus_GLD[0]
    //         }else{
    //             setSelectedStatus(ComboData.proofStatus_GLD.find(item => item.type === searchCriteria.status))
    //         }
    //     }else{
    //         setSelectedStatus(ComboData.proofStatus_GLD[0])      
    //     }
    // }, [searchCriteria]);
        
    React.useEffect(() => {
        setFromDateValue(minDate);
    }, [minDate]);

    React.useEffect(() => {
        setToDateValue(maxDate);
    }, [maxDate]);

    const intl = useIntl();
    const { locale } = intl;

    const marginBottom = 2.5;
    const { reset, register, handleSubmit } = useForm()
    const onSubmit = (data) => {
        let typeArray = [];
        let sentDateFrom = "";
        let sentDateTo = "";

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

        if (fromDateValue != "dd / mm / yyyy" && toDateValue != "dd / mm / yyyy") {
            sentDateFrom = DateUtils.dateValue(fromDateValue)
            sentDateTo = DateUtils.dateValue(toDateValue)
        }
        
        const temp = {
            refNo: data.refNo,
            code: data.code,
            issueId: issueSelected?.id,
            gazettGroup: groupSelected?.title,
            dateFrom: sentDateFrom,
            dateTo: sentDateTo,
            contact: data.contact,
            orgId: (orgSelected?.key && orgSelected?.key > 0) ? orgSelected?.key : "",
            statusKey:status?.key,

        };


        if(status?.type && status?.type != 'all'){
            if (status?.type == "Confirmed"){
                temp["replyed"] = "T";
                temp["action"] = true;
                temp["cancelled"] = false;
            }else if(status?.type == "Re-proofing"){
                temp["replyed"] = "T";
                temp["action"] = false;
                temp["cancelled"] = false;
            }else if(status?.type == "No Reply"){
                temp["replyed"] = "F";
                temp["timeOut"] = "T";
                temp["cancelled"] = false;
            }else if(status?.type == "Cancelled"){
                temp["cancelled"] = true;
            } else{
                temp["replyed"] = "F";
                temp["timeOut"] = "F";
                temp["cancelled"] = false;
            }
        }

        applySearch(temp);
    };

    React.useEffect(() => {
        if (issueComboData && issueComboData.length > 0) {
            setIssueCombo(issueComboData);
            if(searchCriteria.issueId!=undefined){
                setIssueSelected(issueComboData.find(item => item.id === searchCriteria.issueId))
            }
        }
    }, [issueComboData]);

    function resetForm() {
        setType([]);
        setStatus(ComboData.proofStatus[0]);
        setOrgSelected(null);
        setIssueSelected(null);
        setGroupSelected(null);
        setMinDate(DateUtils.dateValue(new Date().setDate(new Date().getDate()-14)))
        setMaxDate(DateUtils.dateValue(new Date()))
        reset({
            refNo:"",
            code:"",
            contact:""
        });
        localStorage.setItem('searchCriteria',"")
    }

    function getIssueLabel(data) {
        let issueYear = data.issueYear
        let volume = data.volume;
        let issueNo = data.issueNo;
        let issueDate = data.issueDate;
        if (locale === 'zh-HK') {
            return issueYear
                + " 第" + volume + "卷,"
                + " 第" + issueNo + "期,"
                + " " + DateUtils.dateFormat(issueDate, "YYYY年MM月DD日")
                + " (" + DateUtils.getWeekdayStr_ZH(issueDate) + ")";
        } else if (locale === 'zh-CN') {
            return issueYear
                + " 第" + volume + "卷,"
                + " 第" + issueNo + "期,"
                + " " + DateUtils.dateFormat(issueDate, "YYYY年MM月DD日")
                + " (" + DateUtils.getWeekdayStr_CN(issueDate) + ")";
        }
        return issueYear
            + " Vol. " + FormatUtils.zeroPad(volume, 3)
            + ", No. " + FormatUtils.zeroPad(issueNo, 2)
            + ", " + DateUtils.dateFormat(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 alignItems={"center"}>
                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                            <TextField
                                fullWidth
                                {...register("refNo")}
                                id='refNo'
                                label="Proof No."
                                defaultValue={searchCriteria.refNo}
                                InputLabelProps={{
                                    shrink: true
                                }}
                            />
                        </Grid>

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

                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                            <Autocomplete
                                {...register("issueId")}
                                disablePortal
                                size="small"
                                id="issueId"
                                options={issueCombo}
                                value={issueSelected}
                                inputValue={(issueSelected?.id) ? getIssueLabel(issueSelected) : ""}
                                getOptionLabel={(option) => getIssueLabel(option)}
                                onChange={(event, newValue) => {
                                    setIssueSelected(newValue);
                                }}
                                sx={{
                                    '& .MuiInputBase-root': { alignItems: 'center' },
                                    '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                    '& .MuiOutlinedInput-root': { height: 40 }
                                }}
                                renderInput={(params) => (
                                    <TextField {...params}
                                        label="Gazette Issue No."
                                        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
                                size="small"
                                id="gazettGroup"
                                options={ComboData.groupTitle}
                                value={groupSelected}
                                inputValue={(groupSelected?.label) ? groupSelected?.label : ""}
                                getOptionLabel={(option) => (option?.label != null ? String(option.label) : "")}
                                onChange={(event, newValue) => {
                                    setGroupSelected(newValue);
                                }}
                                sx={{
                                    '& .MuiInputBase-root': { alignItems: 'center' },
                                    '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                    '& .MuiOutlinedInput-root': { height: 40 }
                                }}
                                renderInput={(params) => (
                                    <TextField {...params}
                                        label="Gazette Group"
                                        InputLabelProps={{
                                            shrink: true
                                        }}
                                    />
                                )}
                            />
                        </Grid>

                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:marginBottom}}>
                            <Grid container spacing={1}>
                                <Grid item xs={6}>
                                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                                        <DemoItem  components={['DatePicker']}>
                                            <DatePicker
                                                id="dateFrom"
                                                // onError={(newError) => setReceiptFromError(newError)}
                                                slotProps={{
                                                    field: { readOnly: true, },
                                                    // textField: {
                                                    //     helperText: receiptFromErrorMessage,
                                                    // },
                                                }}
                                                format="DD/MM/YYYY"
                                                label="Proof Issue Date (From)"
                                                value={minDate === null ? null : dayjs(minDate)}
                                                maxDate={maxDate === null ? null : dayjs(maxDate)}
                                                onChange={(newValue) => {
                                                    // console.log(newValue)
                                                    if(newValue!=null){
                                                        setMinDate(newValue);
                                                    }
                                                }}
                                            />
                                        </DemoItem >
                                    </LocalizationProvider>
                                </Grid>
                               
                                <Grid item xs={6}>         
                                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                                        <DemoItem  components={['DatePicker']}>
                                            <DatePicker
                                                id="dateTo"
                                                // onError={(newError) => setReceiptFromError(newError)}
                                                slotProps={{
                                                    field: { readOnly: true, },
                                                    // textField: {
                                                    //     helperText: receiptFromErrorMessage,
                                                    // },
                                                }}
                                                format="DD/MM/YYYY"
                                                label="Proof Issue Date (To)"
                                                value={maxDate === null ? null : dayjs(maxDate)}
                                                minDate={minDate === null ? null : dayjs(minDate)}
                                                onChange={(newValue) => {
                                                    // console.log(newValue)
                                                    if(newValue!=null){
                                                        setMaxDate(newValue);
                                                    }
                                                }}
                                            />
                                        </DemoItem >
                                    </LocalizationProvider>
                                </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="Client"
                                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
                                {...register("status")}
                                disablePortal={false}
                                id="status"
                                size="small"
                                filterOptions={(options) => options}
                                options={ComboData.proofStatus_GLD}
                                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);
                                    }
                                }}
                                sx={{
                                    '& .MuiInputBase-root': { alignItems: 'center' },
                                    '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                    '& .MuiOutlinedInput-root': { height: 40 }
                                }}
                                renderInput={(params) => (
                                    <TextField
                                        {...params}
                                        label="Status"
                                        InputLabelProps={{ shrink: true }}
                                    />
                                )}
                            />
                        </Grid>

                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                            <OrgComboAutocomplete
                                register={register}
                                value={orgSelected}
                                initialOrgId={searchCriteria.orgId}
                                onChange={(newValue) => {
                                    setOrgSelected(newValue ?? null);
                                }}
                            />
                        </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"
                                color="cancel"
                                onClick={resetForm}
                                >
                                Reset
                            </Button>
                        </Grid>

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

export default SearchPublicNoticeForm;
