// material-ui
import {
    Button,
    Grid, TextField,
    Typography,
    Autocomplete,
} from '@mui/material';
import MainCard from "components/MainCard";
import { useForm } from "react-hook-form";

import { useState,useEffect } from "react";
import * as React from "react";

import * as UrlUtils from "utils/ApiPathConst";
import * as HttpUtils from "utils/HttpUtils";
import * as ComboData from "utils/ComboData";
import {PNSPS_BUTTON_THEME} from "../../../themes/buttonConst";
import {ThemeProvider} from "@emotion/react";
// ==============================|| DASHBOARD - DEFAULT ||============================== //


const OrganizationSearchForm = ({ applySearch, onGridReady, searchCriteria }) => {

    const [type, setType] = useState([]);
    const [creditorSelected, setCreditorSelected] = React.useState(ComboData.CreditorStatus[0]);
    const { reset, register, handleSubmit } = useForm()
    const [onDownload, setOnDownload] = React.useState(false);
    
    useEffect(() => {
        if(searchCriteria.creditor!=undefined){
            setCreditorSelected(ComboData.CreditorStatus.find(item => item.type === searchCriteria.creditor.toString()))
        }else{
            setCreditorSelected(ComboData.CreditorStatus[0]);
        }
    }, [searchCriteria]);

    const onSubmit = (data) => {

        let typeArray = [];

        for (let i = 0; i < type.length; i++) {
            typeArray.push(type[i].label);
        }

        const temp = {
            brNo: data.brNo,
            enCompanyName: data.enCompanyName,
            chCompanyName: data.chCompanyName,
        };
        if(creditorSelected.type == 'true'){
            temp["creditor"] = true;
        }else if(creditorSelected.type == 'false'){
            temp["creditor"] = false;
        }
        applySearch(temp);
    };

    function resetForm() {
        setType([]);
        setCreditorSelected(ComboData.CreditorStatus[0]);
        reset({
            brNo: "",
            enCompanyName: "",
            chCompanyName: "",
        });
    }

    const doExport=()=>{
        setOnDownload(true)
        HttpUtils.fileDownload({
            url: UrlUtils.GET_ORG_EXPORT,
            onResponse:()=>{
                setOnDownload(false)
            },
            onError:()=>{
                setOnDownload(false)
            }
        });
    }

    return (
        <MainCard xs={12} md={12} lg={12}
            border={false}
            content={false}>

            <form onSubmit={handleSubmit(onSubmit)}>
                {/*row 1*/}
                <Grid container sx={{ backgroundColor: '#ffffff', ml: 2, mt: 1}} width="98%">
                    {/*row 1*/}
                    <Grid item justifyContent="space-between" alignItems="center" sx={{mt:1,ml:3,mb:2.5}}>
                        <Typography variant="pnspsFormHeader" >
                            Search
                        </Typography>
                    </Grid>
                    {/*row 2*/}

                    <Grid container display="flex" alignItems={"center"}>
                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                            <TextField
                                fullWidth
                                {...register("brNo")}
                                id='brNo'
                                label="BR No."
                                defaultValue={searchCriteria.brNo}
                                InputLabelProps={{
                                    shrink: true
                                }}
                            />
                        </Grid>

                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                            <TextField
                                fullWidth
                                {...register("enCompanyName")}
                                id="enCompanyName"
                                label="Name (English)"
                                defaultValue={searchCriteria.enCompanyName}
                                InputLabelProps={{
                                    shrink: true
                                }}
                            />
                        </Grid>

                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                            <TextField
                                fullWidth
                                {...register("chCompanyName")}
                                id="chCompanyName"
                                label="Name (Chinese)"
                                defaultValue={searchCriteria.chCompanyName}
                                InputLabelProps={{
                                    shrink: true
                                }}
                            />
                        </Grid>

                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3}}>
                            <Autocomplete
                                    {...register("searchCreditor")}
                                    id="searchCreditor"
                                    size="small"
                                    options={ComboData.CreditorStatus}
                                    value={creditorSelected}
                                    onChange={(event, newValue) => {
                                        if(newValue == null){
                                            setCreditorSelected(ComboData.CreditorStatus[0]);
                                        }else{
                                            setCreditorSelected(newValue);
                                        }
                                        
                                    }}
                                    sx={{
                                        '& .MuiInputBase-root': { alignItems: 'center' },
                                        '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                        '& .MuiOutlinedInput-root': { height: 40 }
                                    }}
                                    getOptionLabel={(option) => (option?.label != null ? String(option.label) : "")}
                                    renderInput={(params) => (
                                        <TextField
                                            {...params}
                                            label="Credit Client/Non-Credit Client"
                                            InputLabelProps={{
                                                shrink: true
                                            }}
                                        />
                                    )}
                                />
                        </Grid>

                    </Grid>


                    {/*last row*/}
                    <Grid container maxWidth justifyContent="flex-end">
                        <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                        <Grid item sx={{mr: 3, mb: 3 }}>
                            <Button
                                variant="contained"
                                onClick={doExport}
                                disabled={onDownload}
                            >
                                Export
                            </Button>
                        </Grid>

                        <Grid item sx={{ mr: 3, mb: 3}}>
                            <Button
                                variant="contained"
                                color="cancel"
                                onClick={resetForm}
                            >
                                Reset
                            </Button>
                        </Grid>

                        <Grid item sx={{ mb: 3}}>
                            <Button
                                variant="contained"
                                type="submit"
                                disabled={onGridReady}
                            >
                                Submit
                            </Button>
                        </Grid>
                        </ThemeProvider>
                    </Grid>
                </Grid>
            </form>
        </MainCard>
    );
};

export default OrganizationSearchForm;
