// material-ui
import {
    Box,
    Grid, Typography
} from '@mui/material';
import MainCard from "../../components/MainCard";
import AdvanceSearchForm from "./AdvanceSearchForm";
import {useContext, useEffect, useState} from "react";
import axios from "axios";
import {apiPath} from "../../auth/utils";
import {GET_APPLICATION_PATH, GET_AWARD_PATH, GET_EVENT_PATH} from "../../utils/ApiPathConst";
import LoadingComponent from "../extra-pages/LoadingComponent";
import * as React from "react";
import EventTable from "../lionerEventSearchPage/EventTable";
import ApplicationTable from "../lionerApplicationSearchPage/ApplicationTable";
import AwardTable from "../lionerAwardSearchPage/AwardTable";
import {useParams} from "react-router-dom";
import {getComboValueByLabel} from "../../utils/CommonFunction";
import {useForm} from "react-hook-form";
import {MODULE_COMBO} from "../../utils/ComboConst";
import {isObjEmpty} from "../../utils/Utils";
import AbilityContext from "../../components/AbilityProvider";
import {LIONER_FORM_THEME, CARD_MAX_WIDTH} from "../../themes/themeConst";
import {ThemeProvider} from "@emotion/react";

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

const DivisionSearchPanel = () => {
    const ability = useContext(AbilityContext);
    const [record, setRecord] = useState([]);
    const [searchCriteria, setSearchCriteria] = useState({});
    const [onReady, setOnReady] = useState(false);
    const [selectedModule, setSelectedModule] = useState(null);
    const params = useParams();
    const { reset, register, handleSubmit, setValue } = useForm()

    useEffect(() => {
        setValue('keyword', params.keyword );
        setSelectedModule(getComboValueByLabel(MODULE_COMBO,params.module));
        setSearchCriteria({
            keyword: params.keyword,
            userSubDivisionId: ability.can('VIEW', 'ALL_RECORD') ? null : localStorage.getItem('subDivisionId'),
        });
    }, []);

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

    useEffect(() => {
        if(selectedModule != null && !isObjEmpty(searchCriteria)){
            getRecordList();
        }
    }, [searchCriteria,selectedModule]);


    function getRecordList() {
        if(selectedModule !== null){
            switch (selectedModule.key){
                case 1:
                    getEventList();
                    break;
                case 2:
                    getApplicationList();
                    break;
                case 3:
                    getAwardList();
                    break;
                default:
                    getEventList();
                    break;
            }
        }
        else{
            getEventList();
        }
    }

    function getEventList(){
        axios.get(`${apiPath}${GET_EVENT_PATH}`,
            {params: searchCriteria}
        )
            .then((response) => {
                if (response.status === 200) {
                    setRecord(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function getApplicationList(){
        axios.get(`${apiPath}${GET_APPLICATION_PATH}`,
            {params: searchCriteria}
        )
            .then((response) => {
                if (response.status === 200) {
                    setRecord(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    function getAwardList(){
        axios.get(`${apiPath}${GET_AWARD_PATH}`,
            {params: searchCriteria}
        )
            .then((response) => {
                if (response.status === 200) {
                    setRecord(response.data.records);
                }
            })
            .catch(error => {
                console.log(error);
                return false;
            });
    }

    const renderByModule = () => {
        if(selectedModule !== null){
            switch (selectedModule.key){
                case 1:
                    return <EventTable
                            recordList={record}
                            pageSize={10}
                        />
                case 2:
                    return <ApplicationTable
                        recordList={record}
                        pageSize={10}
                    />
                case 3:
                    return <AwardTable
                        recordList={record}
                        pageSize={10}
                    />
                default:
                    return <EventTable
                        recordList={record}
                        pageSize={10}
                    />
            }
        }
        else{
            return <EventTable
                recordList={record}
            />
        }
    }

    function applySearch(input,selectedModule) {
        setSearchCriteria(
            {
                ...input,
                userSubDivisionId: ability.can('VIEW', 'ALL_RECORD') ? null : localStorage.getItem('subDivisionId'),
            });
        setSelectedModule(selectedModule);

    }

    return (
        !onReady ?
            <LoadingComponent/>
            :
            <Grid container direction="row" rowSpacing={3} columnSpacing={2.75}>
                <Grid item xs={12} md={12} lg={12}>
                    <Grid container justifyContent="flex-start" alignItems="center">
                        <Grid item xs={3} sx={{mb: -2.25}} >
                            <Box sx={{ display: 'flex', alignItems: 'center'}}>
                                <Typography align="center" variant="h5" >Advsssance Search</Typography>
                            </Box>
                        </Grid>
                    </Grid>
                </Grid>

                {/*row 1*/}
                <Grid item xs={12} md={12} lg={12}>
                    <AdvanceSearchForm
                        reset={reset}
                        register={register}
                        handleSubmit={handleSubmit}
                        applySearch={applySearch}
                        selectedModule={selectedModule}
                    />
                </Grid>
                {/*row 2*/}
                <Grid item xs={12} md={12} lg={12} alignItems="stretch">
                    <MainCard elevation={0}
                              content={false}
                              sx={{width:CARD_MAX_WIDTH}}
                    >
                        <Grid item xs={12} md={12} lg={12} alignItems="stretch">
                            <Grid container direction="row">
                                <Grid item lg={0.1}/>
                                <Grid item xs={12} md={12} lg={11.8}>
                                    <div style={{/*height: '59vh',*/ width:'100%' }}>
                                        <ThemeProvider theme={LIONER_FORM_THEME}>
                                        {renderByModule()}
                                        </ThemeProvider>
                                    </div>
                                </Grid>
                                <Grid item lg={0.1}/>
                            </Grid>
                        </Grid>
                    </MainCard>
                </Grid>

            </Grid>

    );
};

export default DivisionSearchPanel;
