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 useMediaQuery from '@mui/material/useMediaQuery';
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 isMobile = useMediaQuery(theme.breakpoints.down('md'));
  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);
  // let loginuserid = useSelector((state)=>state.logininfo);

  // useEffect(() => {

  //     if (alertmessage) {
  //         dispatch(
  //             openSnackbar({
  //                 open: true,
  //                 message: alertmessage,
  //                 variant: 'alert',
  //                 anchorOrigin: { vertical: 'top', horizontal: 'right' },
  //                 alert: {
  //                     // variant:'info',
  //                     color: 'error',

  //                 }
  //             })
  //         )
  //     }
  // }, [toast])

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

    // 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`, {
            authname: e.target.value,
            configid: 1
            // "contactno": e.target.value,
            // "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/partner/login`, {
              // "authname": username,
              configid: 1,
              contactno: username

              // "password": password
            })
            .then((res) => {
              console.log(res.data);
              if (res.data.status) {
                if (res.data.details.contactno === username) {
                  enqueueSnackbar('login Successfull', {
                    variant: 'success',
                    anchorOrigin: { vertical: 'top', horizontal: 'right' },
                    autoHideDuration: 3000
                  });
                  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('partnerid', res.data.details.partnerid);

                  navigate('/orders');
                  setSubmitting(false);
                }
              }
              console.log(res.data.message);
              setLoading(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 handleClose = () => {
  //     setToast(false)
  // }
  const opentoast = (message) => {
    // setToast(true)

    // setTimeout(() => {
    //     // handleClose();
    //     setToast(false)
    // }, 2000);
    enqueueSnackbar(message, {
      variant: 'error',
      anchorOrigin: { vertical: 'top', horizontal: 'right' },
      autoHideDuration: 2000
    });
  };

  return (
    <>
      {/* <AuthWrapper> */}
      <Box sx={{ minHeight: '100vh' }}>
        {loading && <Loader />}
        {/* <AuthBackground /> */}
        <Grid
          container
          direction="column"
          justifyContent="flex-start"
          sx={{
            minHeight: '100vh'
          }}
        >
          <Grid
            item
            xs={12}
            // sx={{ ml: 3, mt: 3 }}
            sx={{ ml: { xs: 0, md: 3 }, mt: { xs: 3, md: 1 }, textAlign: { xs: 'center', md: 'left' } }}
          >
            <img src={logo} alt="legendary" width={isMobile ? '160px' : '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={{
                    width: { xs: '100%', sm: 'auto' },
                    maxWidth: { xs: 400, lg: 475 },
                    margin: { xs: 2, sm: 2.5, md: 3 },
                    '& > *': {
                      flexGrow: 1,
                      flexBasis: '50%'
                    }
                  }}
                >
                  <Card
                    sx={{
                      position: 'relative',
                      border: '1px solid',
                      borderRadius: { xs: 2, md: 1 },
                      borderColor: theme.palette.divider,
                      boxShadow: { xs: '0 14px 40px rgba(15, 23, 42, 0.10)', md: 'inherit' },
                      p: { xs: 2, md: 2 },
                      width: '100%'
                    }}
                  >
                    {/* <CardHeader title={<Typography variant="h4">Login</Typography>} /> */}
                    {/* <Divider sx={{ borderStyle: 'dashed' }} /> */}
                    {/* <h1>eee</h1> */}
                    {/* <CardHeader> */}

                    <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 item xs={12}>
                                                <AuthLogin isDemo={isLoggedIn} />
                                            </Grid> */}
                    </Grid>
                    <CardContent>
                      <form
                        noValidate
                        onSubmit={(e) => {
                          e.preventDefault();
                        }}
                      >
                        <Grid container spacing={2}>
                          <Grid item xs={12}>
                            {/* <Stack spacing={1}> */}
                            {/* <InputLabel htmlFor="email-login">Email Address</InputLabel>
                                                        <OutlinedInput
                                                            id="email-login"
                                                            type="email"
                                                            value={values.email}
                                                            name="email"
                                                            onBlur={handleBlur}
                                                            onChange={handleChange}
                                                            placeholder="Enter email address"
                                                            fullWidth
                                                            id="username1"
                                                             label="E-mail Address"
                                                             variant="outlined"
                                                            autoComplete='email'
                                                            required
                                                            onChange={usernamecheck}
                                                            error={checkusername}
                                                        error={Boolean(touched.email && errors.email)}
                                                        />
                                                        {touched.email && errors.email && (
                                                        <FormHelperText error id="standard-weight-helper-text-email-login">
                                                            {errors.email}
                                                        </FormHelperText>
                                                    )} */}
                            <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"
                            />
                            {/* </Stack> */}
                          </Grid>
                          <Grid item xs={12}>
                            {/* <Stack spacing={0}> */}
                            {/* <InputLabel htmlFor="password-login">Password</InputLabel> */}
                            {/* <OutlinedInput
                                                            fullWidth
                                                            // error={Boolean(touched.password && errors.password)}
                                                            // id="-password-login"
                                                            // type={showPassword ? 'text' : 'password'}
                                                            // value={values.password}
                                                            // name="password"
                                                            // onBlur={handleBlur}
                                                            // onChange={handleChange}
                                                            // endAdornment={
                                                            //     <InputAdornment position="end">
                                                            //         <IconButton
                                                            //             aria-label="toggle password visibility"
                                                            //             onClick={handleClickShowPassword}
                                                            //             onMouseDown={handleMouseDownPassword}
                                                            //             edge="end"
                                                            //             color="secondary"
                                                            //         >
                                                            //             {showPassword ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                                                            //         </IconButton>
                                                            //     </InputAdornment>
                                                            // }
                                                            placeholder="Enter password"
                                                            // margin="normal"
                                                            // fullWidth
                                                            required
                                                            autoComplete="current-password"
                                                            onChange={(e) => setPassword(e.target.value)}
                                                            type='password' id="password1"
                                                        /> */}
                            {/* {touched.password && errors.password && (
                                                        <FormHelperText error id="standard-weight-helper-text-password-login">
                                                            {errors.password}
                                                        </FormHelperText>
                                                    )} */}

                            {/* </Stack> */}
                            <Link href="#" variant="h6">
                              Forgot password?
                            </Link>
                          </Grid>

                          {/* <Grid item xs={12} sx={{ mt: -1 }}>
                                                <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={2}>
                                                    <FormControlLabel
                                                        control={
                                                            <Checkbox
                                                                checked={checked}
                                                                onChange={(event) => setChecked(event.target.checked)}
                                                                name="checked"
                                                                color="primary"
                                                                size="small"
                                                            />
                                                        }
                                                        label={<Typography variant="h6">Keep me sign in</Typography>}
                                                    />
                                                    <Link variant="h6" component={RouterLink} to={isDemo ? '/auth/forgot-password' : '/forgot-password'} color="text.primary">
                                                        Forgot Password?
                                                    </Link>
                                                </Stack>
                                                  </Grid> */}
                          {/* {errors.submit && (
                                                <Grid item xs={12}>
                                                    <FormHelperText error>{errors.submit}</FormHelperText>
                                                </Grid>
                                                  )} */}
                          <Grid item xs={12}>
                            {/* <AnimateButton> */}
                            <AnimateButton>
                              <Button
                                disabled={submitting}
                                onClick={() => {
                                  loginsend();
                                  // navigate('/dashboard')
                                }}
                                fullWidth
                                size="large"
                                type="submit"
                                variant="contained"
                                color="primary"
                              >
                                Login
                              </Button>
                            </AnimateButton>
                            {/* </AnimateButton> */}
                          </Grid>
                        </Grid>
                        {/* </Grid> */}
                      </form>
                    </CardContent>
                    {/* </CardHeader> */}
                  </Card>
                </Box>
              </Grid>
            </Grid>
          </Grid>
          <Grid
            item
            xs={12}
            // sx={{ m: 3, mt: 1 }}
            sx={{ mb: 1 }}
          >
            {/* <AuthFooter /> */}

            <Container maxWidth="xl">
              <Stack
                direction={{ sx: 'column', md: 'row' }}
                justifyContent={{ sx: 'center', md: 'space-between' }}
                spacing={2}
                // textAlign={{ sx: 'center', md: 'inherit' }}

                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 variant="subtitle2" href="#mantis-privacy" target="_blank" underline="hover" sx={{ml:1}}>Privacy Policy</Typography> */}
                  </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>
                  {/* <Typography
                                    variant="subtitle2"
                                    color="secondary"
                                    component={Link}
                                    href="#"
                                    // target="_blank"
                                    underline="hover"
                                    textAlign='center'
                                >
                                    CA Privacy Notice
                                </Typography> */}
                </Stack>
              </Stack>
            </Container>
          </Grid>
        </Grid>
      </Box>
      {/* </AuthWrapper> */}
    </>
  );
};

export default Login1;
