// material-ui
import {
    Grid, TextField, Typography
} from '@mui/material';
import MainCard from "../../components/MainCard";
import {useContext, useEffect, useState} from "react";
import axios from "axios";
import {apiPath, getUserData} from "../../auth/utils";
import {GET_APPLICATION_PATH, GET_SEARCH_TEMPLATE_COMBO_PATH, GET_SEARCH_TEMPLATE_PATH} from "../../utils/ApiPathConst";
import * as React from "react";
import LoadingComponent from "../extra-pages/LoadingComponent";
import ApplicationTable from "./ApplicationTable";
import ApplicationSearchForm from "./ApplicationSearchForm";
import Qs from "qs";
import Autocomplete from "@mui/material/Autocomplete";
import UploadContext from "../../components/UploadProvider";
import {isObjEmpty} from "../../utils/Utils";
import {notifyLoadSuccess} from "../../utils/CommonFunction";
import AbilityContext from "../../components/AbilityProvider";

import {LIONER_FORM_THEME, CARD_MAX_WIDTH} from "../../themes/themeConst";
import {ThemeProvider} from "@emotion/react";

// ==============================|| DASHBOARD - DEFAULT ||============================== //

const ApplicationSearchPage = () => {

    const [record,setRecord] = useState([]);
    const [searchCriteria, setSearchCriteria] = useState({});
    const [onReady, setOnReady] = useState(false);
    const ability = useContext(AbilityContext);
    const [expanded, setExpanded] = React.useState(true);

    useEffect(() => {
        getApplicationList();
        getTemplateList();
    }, []);

    useEffect(() => {
        setOnReady(true);
    }, [record]);

    useEffect(() => {
        getApplicationList();
    }, [searchCriteria]);

    //=====TEMPLATE RELATED START=====//
    const { setIsUploading } = useContext(UploadContext);
    const [selectedTemplate, setSelectedTemplate] = useState(null);
    const [searchTemplateList, setSearchTemplateList] = useState([]);
    const [refTemplateData, setRefTemplateData] = useState(null);
    const [isUpdating, setIsUpdating] = useState(false);

    function getTemplateList(){
        const userData = getUserData();
        axios.get(`${apiPath}${GET_SEARCH_TEMPLATE_COMBO_PATH}`, {
                params: {
                    "module": "Application",
                    "userId": userData.id
                },
            }
        )
            .then((response) => {
                if (response.status === 200) {
                    setSearchTemplateList(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    useEffect(() => {
        if(!isObjEmpty(selectedTemplate)){
            getTemplateDetail();
        }
        else{
            setRefTemplateData(null);
        }
    }, [selectedTemplate]);

    function getTemplateDetail(){
        setIsUploading(true);
        setIsUpdating(true);
        axios.get(`${apiPath}${GET_SEARCH_TEMPLATE_PATH}/${selectedTemplate.id}`)
            .then((response) => {
                if (response.status === 200) {
                    setRefTemplateData(JSON.parse(response.data.data.criteria));
                    setIsUploading(false);
                    notifyLoadSuccess();
                }
            })
            .catch(error => {
                console.log(error);
                setIsUploading(false);
                return false;
            });
    }

    //=====TEMPLATE RELATED END=====//

    function getApplicationList(){
        const byDivision = {
            ...searchCriteria,
            userSubDivisionId: ability.can('VIEW', 'ALL_RECORD') ? null : localStorage.getItem('subDivisionId'),
        }
        axios.get(`${apiPath}${GET_APPLICATION_PATH}`, {
                params: byDivision,
                paramsSerializer: function (params) {
                    return Qs.stringify(params, { arrayFormat: 'repeat' });
                },
            }
        )
            .then((response) => {
                if (response.status === 200) {
                    setRecord(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function applySearch(input) {
        setSearchCriteria(input);
    }

    return (
        !onReady ?
            <LoadingComponent/>
            :
        <Grid container rowSpacing={3} columnSpacing={2.75}>
            <ThemeProvider theme={LIONER_FORM_THEME}>
            <Grid item xs={12} md={12} lg={12} >
                <Grid container maxWidth justifyContent="space-between" sx={{mt:-2, width:CARD_MAX_WIDTH}}>
                    <Grid item xs={4} s={4} md={4} lg={4}
                          sx={{ mb: -2.25, display: 'flex', alignItems: 'center'}}>
                        <Typography variant="h5">Search Application</Typography>
                    </Grid>
                    <Grid item xs={8} md={5} lg={5} sx={{mb: -2.25}} >
                        <Grid container justifyContent="flex-end">
                            <Grid item xs={4} s={4} md={4} lg={4}
                                  sx={{ display: 'flex', alignItems: 'center'}}>
                                <Typography variant="h5">Search Template:</Typography>
                            </Grid>
                            <Grid item xs={7} s={7} md={7} lg={6}>
                                <Autocomplete
                                    disablePortal
                                    id="search-template-combo"
                                    size="small"
                                    value={selectedTemplate === null ? null : selectedTemplate}
                                    options={searchTemplateList}
                                    onChange={(event, newValue) => {
                                        setSelectedTemplate(newValue);
                                    }}
                                    renderInput={(params) => <TextField {...params} />}
                                />
                            </Grid>
                        </Grid>
                    </Grid>
                </Grid>
            </Grid>

            {/*row 1*/}
            <Grid item xs={12} md={12} lg={12}>
                <ApplicationSearchForm
                    isUpdating={isUpdating}
                    setIsUpdating={setIsUpdating}
                    getTemplateList={getTemplateList}
                    applySearch={applySearch}
                    refTemplateData={refTemplateData}
                    setExpanded={setExpanded}
                    expanded={expanded}
                />
            </Grid>
            {/*row 2*/}
            <Grid item xs={12} md={12} lg={12} sx={{mt:{lg:-1.5}}}>
                <MainCard elevation={0}
                          content={false}
                          sx={{width:CARD_MAX_WIDTH}}
                >
                    <div style={{/*height: expanded? '46vh' : '75vh',*/ width: '100%'}}>
                        <ApplicationTable
                            recordList={record}
                            expanded={expanded}
                            pageSize={10}
                        />
                    </div>
                </MainCard>
            </Grid>
            </ThemeProvider>
        </Grid>

    );
};

export default ApplicationSearchPage;
