import { useState, useEffect } from 'react';
// import { useSelector } from 'react-redux';
// import AuthWrapper from 'sections/auth/AuthWrapper';
import {
  Box,
  Grid,
  Card,
  CardContent,
  Stack,
  TextField,
  Button,
  Typography,
  CardHeader,
  Container,
  Link,
  InputAdornment,
  IconButton
} 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 Loader from 'components/Loader';
import { OpenToast } from 'components/nearle_components/OpenToast';
import { Formik } from 'formik';
import * as Yup from 'yup';
import { Visibility, VisibilityOff } from '@mui/icons-material';

const Login = () => {
  const theme = useTheme();
  const [showPassword, setShowPassword] = useState(false);
  const [loading, setLoading] = useState(false);
  let navigate = useNavigate();
  const [submitting, setSubmitting] = useState(false);
  const LoginSchema = Yup.object().shape({
    username: Yup.string().email('Enter a valid email address').required('Email is required'),
    password: Yup.string().required('Password is required')
  });

  useEffect(() => {
    if (localStorage.getItem('authname')) {
      navigate('/nearle/orders');
    }
  }, []);

  const loginsend = async (values) => {
    console.log('values', values);
    setLoading(true);
    setSubmitting(true);

    try {
      const res = await axios.post(`${process.env.REACT_APP_URL}/users/tenant/weblogin`, {
        authname: values.username,
        configid: 1,
        roleid: 1,
        password: values.password
      });
      console.log(res.data);
      if (res.data.code == 200 && res.data.status == true) {
        OpenToast('Login Successful', 'success', 1000);
        // save to localStorage
        const d = res.data.details;
        localStorage.setItem('tenantname', d.tenantname);
        localStorage.setItem('firstname', d.tenantname);
        localStorage.setItem('authname', d.authname);
        localStorage.setItem('appuserid', d.userid);
        localStorage.setItem('roleid', d.roleid);
        localStorage.setItem('tenantid', d.tenantid);
        localStorage.setItem('applocationid', d.applocationid);
        localStorage.setItem('fullname', d.fullname);
        localStorage.setItem('configid', d.configid);
        localStorage.setItem('locationid', d.locationid);
        localStorage.setItem('moduleid', d.moduleid);
        localStorage.setItem('userid', d.userid);

        setSubmitting(false);
        setLoading(false);

        navigate('/nearle/orders');
      } else {
        OpenToast(res.data.message, 'warning', 2000);
        setLoading(false);
        setSubmitting(false);
      }
    } catch (err) {
      console.log(err);
      setSubmitting(false);
      setLoading(false);
    }
  };

  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: 1 }}>
            <img src={logo} alt="legendary" width="200px" />
          </Grid>
          <Grid
            container
            justifyContent="center"
            alignItems="center"
            sx={{
              minHeight: {
                xs: 'calc(100vh - 180px)',
                sm: 'calc(100vh - 120px)',
                md: 'calc(100vh - 130px)'
              },
              px: 2
            }}
          >
            <Box
              sx={{
                width: '100%',
                maxWidth: { xs: 380, sm: 420, md: 450 }
              }}
            >
              <Card
                sx={{
                  border: '1px solid',
                  borderColor: theme.palette.divider,
                  borderRadius: 1.5,
                  boxShadow: 'inherit',
                  p: 2.5
                }}
              >
                <CardHeader
                  title={
                    <Typography variant="h3" color={'primary'}>
                      Login
                    </Typography>
                  }
                  sx={{ textAlign: 'center', pb: 3 }}
                />
                <CardContent sx={{ pt: 1 }}>
                  <Formik
                    initialValues={{ username: '', password: '' }}
                    validationSchema={LoginSchema}
                    onSubmit={(values) => loginsend(values)}
                  >
                    {({ values, errors, touched, handleChange, handleSubmit, handleBlur }) => (
                      <form noValidate onSubmit={handleSubmit}>
                        <Grid container gap={3}>
                          {/* USERNAME */}
                          <Grid item xs={12}>
                            <TextField
                              fullWidth
                              id="username"
                              name="username"
                              label="E-mail Address"
                              variant="outlined"
                              autoComplete="email"
                              value={values.username}
                              onChange={handleChange}
                              onBlur={handleBlur}
                              error={touched.username && Boolean(errors.username)}
                              helperText={touched.username && errors.username}
                            />
                          </Grid>

                          {/* PASSWORD */}
                          <Grid item xs={12}>
                            <TextField
                              fullWidth
                              id="password"
                              name="password"
                              label="Password"
                              type={showPassword ? 'text' : 'password'}
                              variant="outlined"
                              autoComplete="current-password"
                              value={values.password}
                              onChange={handleChange}
                              onBlur={handleBlur}
                              error={touched.password && Boolean(errors.password)}
                              helperText={touched.password && errors.password}
                              InputProps={{
                                endAdornment: (
                                  <InputAdornment position="end">
                                    <IconButton
                                      aria-label="toggle password visibility"
                                      onClick={() => setShowPassword((prev) => !prev)}
                                      edge="end"
                                    >
                                      {showPassword ? <VisibilityOff /> : <Visibility />}
                                    </IconButton>
                                  </InputAdornment>
                                )
                              }}
                            />
                          </Grid>

                          {/* SUBMIT BUTTON */}
                          <Grid item xs={12}>
                            <AnimateButton>
                              <Button disabled={submitting} fullWidth size="large" type="submit" variant="contained" color="primary">
                                Login
                              </Button>
                            </AnimateButton>
                          </Grid>
                        </Grid>
                      </form>
                    )}
                  </Formik>
                </CardContent>
              </Card>
            </Box>
          </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="https://nearle.in/terms"
                    target="_blank"
                    underline="hover"
                    textAlign="center"
                  >
                    Terms and Conditions
                  </Typography>
                  <Typography
                    variant="subtitle2"
                    color="secondary"
                    component={Link}
                    href="https://nearle.in/privacy"
                    target="_blank"
                    underline="hover"
                    textAlign="center"
                  >
                    Privacy Policy
                  </Typography>
                </Stack>
              </Stack>
            </Container>
          </Grid>
        </Grid>
      </Box>
      {/* </AuthWrapper> */}
    </>
  );
};

export default Login;
