import {
    Box,
    Grid,
    Typography
} from '@mui/material';
import MainCard from "../../components/MainCard";
import FormSigPageSearchForm from "./FormSigPageSearchForm";
import FormSigPageTable from "./FormSigPageTable";
import { useEffect, useState } from "react";
import * as React from "react";
import axios from "axios";
import { apiPath } from "../../auth/utils";
import { GET_FORM_SIG_PAGE_LIST } from "../../utils/ApiPathConst";
import LoadingComponent from "../extra-pages/LoadingComponent";
import { LIONER_FORM_THEME, CARD_MAX_WIDTH } from "../../themes/themeConst";
import { ThemeProvider } from "@emotion/react";

const FormSigPageSearchPanel = () => {
    const [record, setRecord] = useState([]);
    const [searchCriteria, setSearchCriteria] = useState({});
    const [onReady, setOnReady] = useState(false);

    const fetchList = () => {
        const params = {};
        if (searchCriteria.formCode) params.formCode = searchCriteria.formCode;
        if (searchCriteria.sigType) params.sigType = searchCriteria.sigType;
        axios
            .get(`${apiPath}${GET_FORM_SIG_PAGE_LIST}`, { params })
            .then((response) => {
                if (response.status === 200 && response.data?.records) {
                    setRecord(response.data.records);
                }
            })
            .catch((err) => {
                console.error(err);
            });
    };

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

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

    const applySearch = (input) => {
        setSearchCriteria(input || {});
    };

    if (!onReady) return <LoadingComponent />;

    return (
        <Grid container rowSpacing={3} columnSpacing={2.75}>
            <ThemeProvider theme={LIONER_FORM_THEME}>
                <Grid item xs={12} md={12} lg={12} sx={{ mt: -1 }}>
                    <Grid container justifyContent="flex-start" alignItems="center">
                        <Grid item xs={3} sx={{ mb: -2.25 }}>
                            <Box sx={{ display: 'flex', alignItems: 'center' }}>
                                <Typography variant="h5">Form Signature Page Config</Typography>
                            </Box>
                        </Grid>
                    </Grid>
                </Grid>
                <Grid item xs={12} md={12} lg={12}>
                    <FormSigPageSearchForm applySearch={applySearch} />
                </Grid>
                <Grid item xs={12} md={12} lg={12} sx={{ mt: { lg: -1.5 } }}>
                    <MainCard elevation={0} content={false} sx={{ width: CARD_MAX_WIDTH }}>
                        <FormSigPageTable recordList={record} />
                    </MainCard>
                </Grid>
            </ThemeProvider>
        </Grid>
    );
};

export default FormSigPageSearchPanel;
