// material-ui
import {
    Button,
    Grid, 
    TextField,
    Typography,
    Dialog,
    DialogTitle,
    DialogContent,
    DialogActions
} from '@mui/material';
import MainCard from "../../components/MainCard";
import {useForm} from "react-hook-form";
import {useEffect, useState} from "react";
import Autocomplete from '@mui/material/Autocomplete';
import * as React from "react";
import axios from "axios"; // Added missing import
import {apiPath} from "../../auth/utils";
import {useNavigate} from 'react-router-dom';
import {ThemeProvider} from "@emotion/react";
import {LIONER_BUTTON_THEME} from "../../themes/colorConst";
import {USER_GROUP_COMBO} from "../../utils/ComboConst";
import {CARD_MAX_WIDTH} from "../../themes/themeConst";

// ==============================|| USER SEARCH FORM ||============================== //

const UserSearchForm = ({applySearch}) => {
    const navigate = useNavigate();
    const [userGroup, setUserGroup] = useState(null);
    const [locked] = useState(false);
    const [twoFactorEnabled] = useState(false);
    
    // States for Report Dialog
    const [openReportDialog, setOpenReportDialog] = useState(false);
    const [reportDates, setReportDates] = useState({ fromDate: '', toDate: '' });

    const { reset, register, handleSubmit } = useForm();

    const onSubmit = (data) => {
        const temp = {
            username: data.userName,
            fullname: data.fullName,
            groupId: userGroup !== null ? userGroup.id : null,
            email: data.email,
            phone: data.phone,
            locked: locked,
            twoFactorEnabled: twoFactorEnabled,
        };
        applySearch(temp);
    };

    const handleOpenReport = () => setOpenReportDialog(true);
    const handleCloseReport = () => {
        setOpenReportDialog(false);
        setReportDates({ fromDate: '', toDate: '' });
    };

    const handleExport = () => {
        axios.get(`${apiPath}/client/excel-client-consultant-report`, {
            params: reportDates,
            responseType: 'blob',
        })
        .then((response) => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', `Client_Consultant_Report_${reportDates.fromDate}_to_${reportDates.toDate}.xlsx`);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
            handleCloseReport();
        })
        .catch(error => {
            console.error("Export failed", error);
        });
    };

    function resetForm(){
        setUserGroup(null);
        reset();
    }

    function createNewUser(){
        navigate('/user/-1');
    }

    return (
        <MainCard xs={12} md={12} lg={12}
                  content={false}
                  sx={{width:CARD_MAX_WIDTH}}
        >
            <form onSubmit={handleSubmit(onSubmit)}>
                <Grid sx={{mb:2}}/>
                <Grid container alignItems={"center"}>
                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5 }}>
                        <Typography variant="lionerLabel" component="span">Username</Typography>
                        <TextField fullWidth {...register("userName")} inputProps={{maxLength: 50}} id='userName' autoComplete="off" />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5 }}>
                        <Typography variant="lionerLabel" component="span">Full Name</Typography>
                        <TextField fullWidth {...register("fullName")} inputProps={{maxLength: 90}} id="fullName" autoComplete="off" />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5 }}>
                        <Typography variant="lionerLabel" component="span">User Group</Typography>
                        <Autocomplete
                            disablePortal
                            id="user-group-combo"
                            size="small"
                            value={userGroup}
                            options={USER_GROUP_COMBO}
                            onChange={(event, newValue) => setUserGroup(newValue)}
                            renderInput={(params) => <TextField {...params}/>}
                        />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5 }}>
                        <Typography variant="lionerLabel" component="span">Email</Typography>
                        <TextField fullWidth {...register("email")} inputProps={{maxLength: 120}} id="email" autoComplete="off" />
                    </Grid>

                    <Grid item xs={9} s={6} md={5} lg={3} sx={{ml:3, mr:3, mb:0.5 }}>
                        <Typography variant="lionerLabel" component="span">Phone</Typography>
                        <TextField fullWidth {...register("phone")} inputProps={{maxLength: 30}} id="phone" autoComplete="off" />
                    </Grid>
                </Grid>

                <Grid container justifyContent="space-between" sx={{mt:1.5, mb:2}}>
                    <ThemeProvider theme={LIONER_BUTTON_THEME}>
                        <Grid item>
                            <Grid container>
                                <Grid item sx={{ml:3, mr:1.5}}>
                                    <Button variant="contained" type="submit" color="save">Search</Button>
                                </Grid>
                                <Grid item sx={{ml:1.5, mr:1.5}}>
                                    <Button variant="contained" onClick={resetForm} color="cancel">Clear</Button>
                                </Grid>
                                <Grid item sx={{ml:1.5, mr:3}}>
                                    <Button variant="contained" onClick={handleOpenReport} color="primary">
                                        Client Consultant Report
                                    </Button>
                                </Grid>
                            </Grid>
                        </Grid>

                        <Grid item sx={{ml:3, mr:3, mb:0.5 }}>
                            <Button variant="contained" onClick={createNewUser} color="create">New User</Button>
                        </Grid>
                    </ThemeProvider>
                </Grid>
            </form>

            {/* Report Criteria Dialog */}
            <Dialog open={openReportDialog} onClose={handleCloseReport} fullWidth maxWidth="xs">
                <DialogTitle>Export Client Consultant Report</DialogTitle>
                <DialogContent>
                    <Grid container spacing={2} sx={{ mt: 0.5 }}>
                        <Grid item xs={12}>
                            <Typography variant="lionerLabel">From Date</Typography>
                            <TextField
                                fullWidth
                                type="date"
                                InputLabelProps={{ shrink: true }}
                                value={reportDates.fromDate}
                                onChange={(e) => setReportDates({ ...reportDates, fromDate: e.target.value })}
                            />
                        </Grid>
                        <Grid item xs={12}>
                            <Typography variant="lionerLabel">To Date</Typography>
                            <TextField
                                fullWidth
                                type="date"
                                InputLabelProps={{ shrink: true }}
                                value={reportDates.toDate}
                                onChange={(e) => setReportDates({ ...reportDates, toDate: e.target.value })}
                            />
                        </Grid>
                    </Grid>
                </DialogContent>
                <DialogActions sx={{ p: 3 }}>
                    <Button onClick={handleCloseReport} color="inherit">Cancel</Button>
                    <ThemeProvider theme={LIONER_BUTTON_THEME}>
                        <Button 
                            onClick={handleExport} 
                            variant="contained" 
                            color="save" 
                            disabled={!reportDates.fromDate || !reportDates.toDate}
                        >
                            Export Excel
                        </Button>
                    </ThemeProvider>
                </DialogActions>
            </Dialog>
        </MainCard>
    );
};

export default UserSearchForm;