// material-uistatus
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";

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, onGridReady }) => {
    const intl = useIntl();
    const [type, setType] = React.useState([]);
    const [status, setStatus] = React.useState(localStorage.getItem('userData').creditor?ComboData.publicNoticeStatic_Creditor[0]:ComboData.publicNoticeStatic[0]);

    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");
    // const [selectedLabelsString, setSelectedLabelsString] = React.useState('');

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

    React.useEffect(() => {
        if(searchCriteria.status!=undefined){
            if(localStorage.getItem('userData').creditor){
                if(searchCriteria.status === ""){
                    ComboData.publicNoticeStatic_Creditor[0]
                }else{
                    setStatus(ComboData.publicNoticeStatic_Creditor.find(item => item.type === searchCriteria.status))
                }
            }else{
                if(searchCriteria.status === ""){
                    ComboData.publicNoticeStatic[0]
                }else{
                    setStatus(ComboData.publicNoticeStatic.find(item => item.type === searchCriteria.status))
                }
            }
        }else{
            if(localStorage.getItem('userData').creditor){
                setStatus(ComboData.publicNoticeStatic_Creditor[0])
            }else{
                setStatus(ComboData.publicNoticeStatic[0])
            }
        }
    }, [searchCriteria]);

    React.useEffect(() => {
        setFromDateValue(minDate);
    }, [minDate]);

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

    const onSubmit = (data) => {
        data.status = status.type;
        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 = {
            appNo: data.appNo,
            dateFrom: sentDateFrom,
            dateTo: sentDateTo,
            contact: data.contact,
            careOf: data.careOf?data.careOf:"",
            status: (data.status === "" || data.status.includes('all')) ? "" : data.status,
            start:0,
            limit:10
        };
        applySearch(temp);
    };

    function resetForm() {
        setType([]);
        setStatus(localStorage.getItem('userData').creditor?ComboData.publicNoticeStatic_Creditor[0]:ComboData.publicNoticeStatic[0]);
        setMinDate(DateUtils.dateValue(new Date().setDate(new Date().getDate()-14)))
        setMaxDate(DateUtils.dateValue(new Date()))
        reset({
            appNo:""
        });
        localStorage.setItem('searchCriteria',"")
    }

    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 }}>
                        <LocalizationProvider dateAdapter={AdapterDayjs} localeText={DateUtils.getPickerLocaleText(intl.locale)}>
                            <DemoItem  components={['DatePicker']}>
                                <DatePicker
                                    id="dateFrom"
                                    // onError={(newError) => setReceiptFromError(newError)}
                                    slotProps={{
                                        field: { readOnly: true, },
                                        // textField: {
                                        //     helperText: receiptFromErrorMessage,
                                        // },
                                    }}
                                    format="DD/MM/YYYY"
                                    aria-label={intl.formatMessage({id: 'submitDateFrom'})}
                                    label={intl.formatMessage({id: 'submitDateFrom'})}
                                    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={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                        <LocalizationProvider dateAdapter={AdapterDayjs} localeText={DateUtils.getPickerLocaleText(intl.locale)}>
                            <DemoItem  components={['DatePicker']}>
                                <DatePicker
                                    id="dateTo"
                                    // onError={(newError) => setReceiptFromError(newError)}
                                    slotProps={{
                                        field: { readOnly: true, },
                                        // textField: {
                                        //     helperText: receiptFromErrorMessage,
                                        // },
                                    }}
                                    format="DD/MM/YYYY"
                                    label={intl.formatMessage({id: 'submitDateTo'})}
                                    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>
                    {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={intl.formatMessage({id: 'careOf'})}
                                aria-label={intl.formatMessage({id: 'careOf'})}
                                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
                            {...register("status")}
                            id="status"
                            size="small"
                            disableClearable
                            // filterOptions={(options)=>options}
                            options={
                                localStorage.getItem('userData').creditor ?
                                    ComboData.publicNoticeStatic_Creditor :
                                    ComboData.publicNoticeStatic
                            }
                            value={status}
                            // inputValue={status?.labelCht}
                            getOptionLabel={(option) => {
                                if (option == null || option.label == null) return "";
                                const s = intl.formatMessage({ id: option.label });
                                return typeof s === "string" ? s : String(s ?? "");
                            }}
                            onChange={(event, newValue) => {
                                if(newValue ==null){
                                    setStatus(localStorage.getItem('userData').creditor?ComboData.publicNoticeStatic_Creditor[0]:ComboData.publicNoticeStatic[0]);
                                }else{
                                    setStatus(newValue);
                                }
                            }}
                            sx={{
                                '& .MuiInputBase-root': { alignItems: 'center' },
                                '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                '& .MuiOutlinedInput-root': { height: 40 }
                            }}
                            renderInput={(params) => (
                                <TextField {...params}
                                    label={intl.formatMessage({id: 'status'})}
                                    aria-label={intl.formatMessage({id: 'status'})}
                                    InputLabelProps={{
                                        shrink: true
                                    }}
                                />
                            )}
                            clearText={intl.formatMessage({ id: "muiClear" })}
                            closeText={intl.formatMessage({ id: "muiClose" })}
                            openText={intl.formatMessage({ id: "muiOpen" })}
                            noOptionsText={intl.formatMessage({ id: "muiNoOptions" })}
                        // 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) => {
                                if (option == null || option.label == null) return "";
                                const s = intl.formatMessage({ id: option.label });
                                return typeof s === "string" ? s : String(s ?? "");
                            }}
                            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>


                {/*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"
                            disabled={onGridReady}
                            aria-label={intl.formatMessage({id: 'search'})}
                        >
                            <Typography variant="pnspsButtonText">
                                <FormattedMessage id="search"/>
                            </Typography>
                        </Button>
                    </Grid>
                    </ThemeProvider>
                </Grid>
            </form>
        </MainCard>
    );
};

export default SearchPublicNoticeForm;
