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

import { useState, useEffect} from "react";
import {PNSPS_BUTTON_THEME} from "../../../themes/buttonConst";
import {ThemeProvider} from "@emotion/react";
// ==============================|| DASHBOARD - DEFAULT ||============================== //


const UserSearchForm_Organization = ({applySearch, orgComboData, onGridReady, searchCriteria}) => {

    const [type, setType] = useState([]);
    const [accountFilter, setAccountFilter] = useState("All");
    const [orgCombo, setOrgCombo] = useState();
    const [orgSelected, setOrgSelected] = useState({});

    const { reset, register, handleSubmit } = useForm()
    
    useEffect(() => {
        if(searchCriteria.accountFilter!=undefined){
            if(searchCriteria.accountFilter === ""){
                setAccountFilter("All")
            }else{
                setAccountFilter(searchCriteria.accountFilter)
            }
        }else{
            setAccountFilter("All")    
        }
    }, [searchCriteria]);

    const onSubmit = (data) => {

        let typeArray = [];

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

        const temp = {
            username: data.userName,
            fullenName: data.fullenName,
            email: data.email,
            contactTel: data.phone,
            contactPerson: data.contactPerson,
            brNoStr: data.brNoStr,
            orgName: orgSelected?.name ? orgSelected?.name : "",
            accountFilter: accountFilter=="All"?null:accountFilter,
            start:0,
            limit:10
        };
        applySearch(temp);
    };

    useEffect(() => {
        if (orgComboData && orgComboData.length > 0) {
            setOrgCombo(orgComboData);
            if(searchCriteria.orgName!=undefined){
                setOrgSelected(orgComboData.find(item => item.name === searchCriteria.orgName))
            }
        }
    }, [orgComboData]);

    function resetForm(){
        setType([]);
        setAccountFilter("All");
        setOrgSelected({});
        reset({
            userName:"",
            fullenName:"",
            email:"",
            phone:"",
            contactPerson:"",
            brNoStr:"",
        });
        localStorage.setItem('searchCriteria',"")
    }

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

            <form onSubmit={handleSubmit(onSubmit)} >
                <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"}>
                        {
                            orgCombo ?
                                <Grid item xs={9} s={6} md={5} lg={3} sx={{ ml: 3, mr: 3, mb: 3 }}>
                                    <Autocomplete
                                        {...register("orgId")}
                                        disablePortal
                                        id="orgId"
                                        options={orgCombo}
                                        groupBy={(option) => option.groupType}
                                        size="small"
                                        value={orgSelected}
                                        getOptionLabel={(option) => option.name? option.name : ""}
                                        inputValue={orgSelected ? orgSelected.name!=undefined?orgSelected.name:"" : ""}

                                        onChange={(event, newValue) => {
                                            if (newValue !== null) {
                                                setOrgSelected(newValue);
                                            }else{
                                                setOrgSelected({});
                                            }
                                        }}
                                        sx={{
                                            '& .MuiInputBase-root': { alignItems: 'center' },
                                            '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                            '& .MuiOutlinedInput-root': { height: 40 }
                                        }}
                                        renderInput={(params) => (
                                            <TextField {...params}
                                                label="Organisation"
                                                InputLabelProps={{
                                                    shrink: true
                                                }}
                                            />
                                        )}
                                        renderGroup={(params) => (
                                            <Grid item key={params.key}>
                                                <Typography fontSize={20} fontStyle="italic" p={1}>
                                                {params.group}
                                                </Typography>
                                                {params.children}
                                            </Grid>
                                        )}
                                    />
                                </Grid>
                                : <></>
                        }

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

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

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

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

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

                        <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:3}}>
                                     <Autocomplete
                                      {...register("accountFilter")}
                                        disablePortal={false}
                                        id="accountFilter"
                                        size="small"
                                        options={["All", "Active","Locked","Not Verified"]}
                                        value={accountFilter}
                                        onChange={(event, newValue) => {
                                            if (newValue !== null){
                                                setAccountFilter(newValue);
                                            }else{
                                                setAccountFilter("All");
                                            }
                                        }}
                                        sx={{
                                            '& .MuiInputBase-root': { alignItems: 'center' },
                                            '& .MuiAutocomplete-endAdornment': { top: '50%', transform: 'translateY(-50%)' },
                                            '& .MuiOutlinedInput-root': { height: 40 }
                                        }}
                                        renderInput={(params) => (
                                        <TextField {...params}
                                            label="Status"
                                            InputLabelProps={{
                                                shrink: true
                                            }}
                                        />
                                        )}
                                    />
                        </Grid>
                        {/*<Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:3}}>*/}
                        {/*    <TextField*/}
                        {/*        fullWidth*/}
                        {/*        {...register("subDivisionId")}*/}
                        {/*        id="subDivision"*/}
                        {/*        label="Sub-Division"*/}
                        {/*    />*/}
                        {/*</Grid>*/}

                    </Grid>


                    {/*last row*/}
                    <Grid container maxWidth justifyContent="flex-end">
                        <ThemeProvider theme={PNSPS_BUTTON_THEME}>
                        <Grid item sx={{ml:3, 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 UserSearchForm_Organization;
