// material-ui
import {
    Button,
    Grid, TextField, Typography,
} from '@mui/material';
import MainCard from "../../components/MainCard";
import {useForm} from "react-hook-form";
import * as React from "react";
import {AdapterDayjs} from "@mui/x-date-pickers/AdapterDayjs";
import {DemoItem} from "@mui/x-date-pickers/internals/demo";
import {DatePicker} from "@mui/x-date-pickers/DatePicker";
import dayjs from "dayjs";
import {useEffect, useState} from "react";
import {LocalizationProvider} from "@mui/x-date-pickers/LocalizationProvider";
import Autocomplete from "@mui/material/Autocomplete";
import {tableNameCombo} from "../../utils/ComboConst";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {GET_USER_AUDIT_COMBO_LIST} from "../../utils/ApiPathConst";
import {LIONER_BUTTON_THEME, GENERAL_RED_COLOR} from "../../themes/colorConst";
import {ThemeProvider} from "@emotion/react";
import {CARD_MAX_WIDTH} from "../../themes/themeConst";
// ==============================|| DASHBOARD - DEFAULT ||============================== //

const AuditLogSearchForm = ({applySearch}) => {

    const { reset, register, handleSubmit } = useForm()
    const [fromDate, setFromDate] = useState(null);
    const [toDate, setToDate] = useState(null);
    const [selectedTableName, setSelectedTableName] = useState(null);
    const [selectedUser, setSelectedUser] = useState(null);
    const [userCombo, setUserCombo] = useState([]);
    const [errors, setErrors] = useState({});
    const [fromError, setFromError] = React.useState(null);
    const [toError, setToError] = React.useState(null);
    const fromErrorMessage = React.useMemo(() => {
        switch (fromError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [fromError]);

    const toErrorMessage = React.useMemo(() => {
        switch (toError) {
            case 'invalidDate': {
                return "Invalid date";
            }
        }
    }, [toError]);

    const onSubmit = (data) => {
        const formErrors = {};

        if(selectedTableName === null){
            formErrors.tableName = 'Table name is required';

        }
        if(fromDate === null || toDate === null ) {
            formErrors.date = 'Date Range is required';
        }

        setErrors(formErrors);

        if (Object.keys(formErrors).length === 0) {
            const temp = {
                tableName: selectedTableName == null ? null : selectedTableName.value,
                recordName: data.recordName,
                modifiedBy: selectedUser == null ? null : selectedUser.id,
                fromDate: fromDate === null ? null : dayjs(fromDate).format('YYYY-MM-DD'),
                toDate: toDate === null ? null : dayjs(toDate).format('YYYY-MM-DD'),
            }
            applySearch(temp);
        }
    };

    useEffect(() => {
        axios.get(`${apiPath}${GET_USER_AUDIT_COMBO_LIST}`)
            .then((response) => {
                if (response.status === 200) {
                    setUserCombo(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }, []);

    function resetForm(){
        setFromDate(null);
        setToDate(null);
        setSelectedUser(null);
        setSelectedTableName(null);
        reset();
    }

    return (
        <MainCard xs={12} md={12} lg={12}
                  content={false}
                  sx={{width:CARD_MAX_WIDTH}}
        >

            <form onSubmit={handleSubmit(onSubmit)}>

                {/*row 1*/}
                <Grid sx={{mb:2}}/>

                {/*row 2*/}
                <Grid container alignItems={"flex-start"}>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5 }}>
                        <Typography variant="lionerLabel" component="span">
                            Table
                            <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                        </Typography>
                        <Autocomplete
                            required
                            disablePortal
                            id="table-name-combo"
                            size="small"
                            value={selectedTableName === null? null : selectedTableName}
                            options={tableNameCombo}
                            onChange={(event, newValue) => {
                                setSelectedTableName(newValue);
                            }}
                            renderInput={(params) => <TextField
                                {...params}
                                error={!!errors.tableName}
                                helperText={errors.tableName}
                            />}
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5 }}>
                        <Typography variant="lionerLabel" component="span">
                            Modified By
                        </Typography>
                        <Autocomplete
                            required
                            disablePortal
                            id="user-combo"
                            size="small"
                            value={selectedUser === null? null : selectedUser}
                            options={userCombo}
                            onChange={(event, newValue) => {
                                setSelectedUser(newValue);
                            }}
                            renderInput={(params) => <TextField {...params} />}
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5 }}>
                        <Typography variant="lionerLabel" component="span">
                            Record Name
                        </Typography>
                        <TextField
                            fullWidth
                            inputProps={{maxLength: 255}}
                            {...register("recordName")}
                            id='recordName'
                            autoComplete="off"
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5 }}>
                        <Typography variant="lionerLabel" component="span">
                            Modified Date
                            <Typography sx={{ color: GENERAL_RED_COLOR }} component="span">*</Typography>
                        </Typography>
                        <Grid container>
                            <Grid item xs={5.25} s={5.25} md={5.25} lg={5.5}>
                                <LocalizationProvider dateAdapter={AdapterDayjs}>
                                    <DemoItem  components={['DatePicker']}>
                                        <DatePicker
                                            id="fromDate"
                                            value={fromDate === null ? null : dayjs(fromDate)}
                                            onChange={(newValue) => setFromDate(newValue)}
                                            format="DD/MM/YYYY"
                                            onError={(newError) => setFromError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    error: !!errors.date || fromError,
                                                    helperText: fromError ? fromErrorMessage :errors.date,
                                                },
                                            }}
                                        />
                                    </DemoItem >
                                </LocalizationProvider>
                            </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'}}>
                                To
                            </Grid>

                            <Grid item xs={5.25} s={5.25} md={5.25} lg={5.5}>
                                <LocalizationProvider dateAdapter={AdapterDayjs}>
                                    <DemoItem  components={['DatePicker']}>
                                        <DatePicker
                                            id="toDate"
                                            //label="To Date"
                                            value={toDate === null ? null : dayjs(toDate)}
                                            format="DD/MM/YYYY"
                                            onChange={(newValue) => setToDate(newValue)}
                                            onError={(newError) => setToError(newError)}
                                            slotProps={{
                                                field: { clearable: true },
                                                textField: {
                                                    error: !!errors.date || toError,
                                                    helperText: toErrorMessage
                                                },
                                            }}
                                        />
                                    </DemoItem >
                                </LocalizationProvider>
                            </Grid>
                        </Grid>
                    </Grid>
                </Grid>


                {/*last row*/}
                <Grid container maxWidth justifyContent="flex-start" sx={{mb:2, mt:1.5}}>
                    <ThemeProvider theme={LIONER_BUTTON_THEME}>
                        <Grid item sx={{ml:3, mr:1.5}}>
                            <Button
                                size="medium"
                                variant="contained"
                                type="submit"
                                color="save"
                                disabled={fromError || toError}
                            >
                                Search
                            </Button>
                        </Grid>

                        <Grid item sx={{ml:1.5, mr:3 }}>
                            <Button
                                size="medium"
                                variant="contained"
                                onClick={resetForm}
                                color="cancel">
                                Clear
                            </Button>
                        </Grid>
                    </ThemeProvider>
                </Grid>
            </form>
        </MainCard>
    );
};

export default AuditLogSearchForm;
