import { useState, useEffect } from 'react';
// import { useSelector } from 'react-redux';
// import AuthWrapper from 'sections/auth/AuthWrapper';
import {
  Box,
  Grid,
  Card,
  CardContent,
  // CardHeader,
  Stack,
  //  Divider,
  // InputLabel,
  // OutlinedInput,
  TextField,
  Button,
  Typography,
  CardHeader,
  Container,
  Link
} from '@mui/material';
import { useTheme } from '@mui/material/styles';
import AnimateButton from 'components/@extended/AnimateButton';

import logo from 'assets/images/logo-nearle1.png';

import axios from 'axios';
import { useNavigate } from 'react-router-dom';
// import { openSnackbar } from 'store/reducers/snackbar';
// import { useDispatch } from 'react-redux';
import Loader from 'components/Loader';
import { enqueueSnackbar } from 'notistack';

const Login = () => {
  const theme = useTheme();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [alertmessage, setAlertmessage] = useState('');
  const [checkusername, setCheckusername] = useState(false);
  // const [toast, setToast] = useState(false);
  const [loading, setLoading] = useState(false);
  let navigate = useNavigate();
  // let dispatch = useDispatch();
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    if (
      localStorage.getItem('authname')
      //  || localStorage.getItem("appuserid")
    ) {
      navigate('/orders');
    }

    // console.log(alertmessage)
  }, []);

  const usernamecheck = async (e) => {
    e.preventDefault();
    setUsername(e.target.value);
    if (e.target.value) {
      try {
        // await axios.post(`${process.env.REACT_APP_URL}/auth/login`, {
        //     "authname": e.target.value
        // })
        await axios
          // .post(`${process.env.REACT_APP_URL}/users/login`, {
          .post(`${process.env.REACT_APP_URL}/users/tenant/login`, {
            authname: e.target.value,
            configid: 1,
            password: 'admin'
          })
          .then((res) => {
            console.log(res.data);
            if (res.data.details.authname === e.target.value) {
              setUsername(e.target.value);
              setCheckusername(false);
            } else {
              setCheckusername(true);
            }
            // if (res.data.authname === e.target.value) {

            //     setUsername(e.target.value);
            //     setCheckusername(false);
            // }
          })
          .catch((err) => {
            // if (err.response.data.message === 'No user found') {

            setCheckusername(true);
            // }
          });
      } catch (err) {
        console.log(err);
      }
    }
  };

  const loginsend = async () => {
    // e.preventDefault();
    setLoading(true);

    if (password && username) {
      if (password == 'admin') {
        setSubmitting(true);
        try {
          await axios
            // .post(`${process.env.REACT_APP_URL}/users/login`, {
            .post(`${process.env.REACT_APP_URL}/users/tenant/login`, {
              authname: username,
              configid: 1,
              password: password
            })
            .then((res) => {
              console.log(res.data);
              if (res.data.details.authname === username) {
                // setAlertmessage('login Successfull');
                setLoading(false);
                // dispatch(
                //     openSnackbar({
                //         open: true,
                //         message: 'login Successfull',
                //         variant: 'alert',
                //         anchorOrigin: { vertical: 'top', horizontal: 'right' },
                //         alert: {
                //             color: 'success'
                //         }
                //     })
                // )
                enqueueSnackbar('login Successfull', {
                  variant: 'success',
                  anchorOrigin: { vertical: 'top', horizontal: 'right' },
                  autoHideDuration: 1000
                });
                setUsername('');
                setPassword('');
                localStorage.setItem('firstname', res.data.details.tenantname);
                localStorage.setItem('authname', res.data.details.authname);
                localStorage.setItem('appuserid', res.data.details.userid);
                localStorage.setItem('roleid', res.data.details.roleid);
                localStorage.setItem('tenantid', res.data.details.tenantid);
                localStorage.setItem('applocationid', res.data.details.applocationid);
                localStorage.setItem('fullname', res.data.details.fullname);
                localStorage.setItem('configid', res.data.details.configid);
                localStorage.setItem('locationid', res.data.details.locationid);
                localStorage.setItem('moduleid', res.data.details.moduleid);
                localStorage.setItem('userid', res.data.details.userid);

                navigate('/orders');
                setSubmitting(false);
              } else {
                opentoast('Login Error');
                setLoading(false);
                setSubmitting(false);
              }
            })
            .catch((err) => {
              console.log(err);

              // setAlertmessage('Invalid Data');
              // if(err.message == 'Network Error'){
              opentoast(err.message);
              // }else{
              //     opentoast('Invalid Data');

              // }
              setLoading(false);
              setSubmitting(false);
              console.log(err.message);
            });
        } catch (err) {
          console.log(err);
          setLoading(false);
          setSubmitting(false);
        }
      } else {
        opentoast('Password is Incorrect');
        setLoading(false);
      }
    } else {
      // let el2 = document.getElementById('toastid');
      // el2.classList.add('d-block');
      // el2.classList.remove('d-none');
      setAlertmessage('Fill All required fields');
      opentoast('Fill All required fields');
      setLoading(false);
    }
  };

  const opentoast = (message) => {
    enqueueSnackbar(message, {
      variant: 'error',
      anchorOrigin: { vertical: 'top', horizontal: 'right' },
      autoHideDuration: 2000
    });
  };

  return (
    <>
      {/* <AuthWrapper> */}
      <Box sx={{ minHeight: '100vh' }}>
        {loading && <Loader />}

        <Grid
          container
          direction="column"
          justifyContent="flex-start"
          sx={{
            minHeight: '100vh'
          }}
        >
          <Grid
            item
            xs={12}
            // sx={{ ml: 3, mt: 3 }}
            sx={{ ml: 3, mt: 1 }}
          >
            <img src={logo} alt="legendary" width="200px" />
          </Grid>
          <Grid item xs={12}>
            <Grid
              item
              xs={12}
              container
              justifyContent="center"
              alignItems="center"
              // sx={{ minHeight: { xs: 'calc(100vh - 210px)', sm: 'calc(100vh - 134px)', md: 'calc(100vh - 112px)' } }}
              sx={{ minHeight: { xs: 'calc(100vh - 210px)', sm: 'calc(100vh - 134px)', md: 'calc(100vh - 140px)' } }}
            >
              <Grid item>
                {/* <AuthCard>{children}</AuthCard> */}
                <Box
                  sx={{
                    maxWidth: { xs: 400, lg: 475 },
                    margin: { xs: 2.5, md: 3 },
                    '& > *': {
                      flexGrow: 1,
                      flexBasis: '50%'
                    }
                  }}
                >
                  <Card
                    sx={{
                      position: 'relative',
                      border: '1px solid',
                      borderRadius: 1,
                      borderColor: theme.palette.divider,
                      boxShadow: 'inherit',
                      p: 2,
                      width: '100%'
                    }}
                  >
                    <Grid container spacing={3}>
                      <Grid item xs={12}>
                        <Stack direction="row" justifyContent="flex-start" alignItems="baseline" sx={{ mb: { xs: -0.5, sm: 0.5 } }}>
                          <CardHeader title={<Typography variant="h3">Login</Typography>} />
                        </Stack>
                      </Grid>
                    </Grid>
                    <CardContent>
                      <form
                        noValidate
                        onSubmit={(e) => {
                          e.preventDefault();
                        }}
                      >
                        <Grid container spacing={2}>
                          <Grid item xs={12}>
                            <TextField
                              margin="normal"
                              fullWidth
                              id="username1"
                              label="E-mail Address"
                              variant="outlined"
                              autoComplete="email"
                              required
                              onChange={usernamecheck}
                              error={checkusername}
                            />
                            <TextField
                              margin="normal"
                              fullWidth
                              required
                              autoComplete="current-password"
                              onChange={(e) => setPassword(e.target.value)}
                              type="password"
                              id="password1"
                              label="Password"
                              variant="outlined"
                            />
                          </Grid>
                          <Grid item xs={12}>
                            <Link href="#" variant="h6">
                              Forgot password?
                            </Link>
                          </Grid>

                          <Grid item xs={12}>
                            <AnimateButton>
                              <Button
                                disabled={submitting}
                                onClick={() => {
                                  loginsend();
                                }}
                                fullWidth
                                size="large"
                                type="submit"
                                variant="contained"
                                color="primary"
                              >
                                Login
                              </Button>
                            </AnimateButton>
                          </Grid>
                        </Grid>
                      </form>
                    </CardContent>
                  </Card>
                </Box>
              </Grid>
            </Grid>
          </Grid>
          <Grid item xs={12} sx={{ mb: 1 }}>
            <Container maxWidth="xl">
              <Stack
                direction={{ sx: 'column', md: 'row' }}
                justifyContent={{ sx: 'center', md: 'space-between' }}
                spacing={2}
                alignItems={{ sx: 'center', md: 'inherit' }}
                width="100%"
              >
                <Stack direction="row" justifyContent="center" spacing={1}>
                  <Typography variant="subtitle2" color="secondary" component="span" sx={{ display: 'flex' }}>
                    &copy; All rights reserved
                  </Typography>
                </Stack>

                <Stack
                  direction={{ sx: 'column', md: 'row' }}
                  spacing={{ sx: 1, md: 3 }}
                  textAlign={{ sx: 'center', md: 'inherit' }}
                  alignItems={{ sx: 'center', md: 'inherit' }}
                  // width='100%'
                >
                  <Typography
                    variant="subtitle2"
                    color="secondary"
                    component={Link}
                    href="#"
                    // target="_blank"
                    underline="hover"
                    textAlign="center"
                  >
                    Terms and Conditions
                  </Typography>
                  <Typography
                    variant="subtitle2"
                    color="secondary"
                    component={Link}
                    href="#"
                    // target="_blank"
                    underline="hover"
                    textAlign="center"
                  >
                    Privacy Policy
                  </Typography>
                </Stack>
              </Stack>
            </Container>
          </Grid>
        </Grid>
      </Box>
      {/* </AuthWrapper> */}
    </>
  );
};

export default Login;
