import { useState, useEffect } from 'react';
import { enqueueSnackbar, closeSnackbar } from 'notistack';
import AnimateButton from 'components/@extended/AnimateButton';
import OtpInput from 'react18-input-otp';

import { Box, Card, CardContent, Stack, TextField, Button, Typography, Link, FormLabel, IconButton, InputAdornment } from '@mui/material';
import { useTheme } from '@mui/material/styles';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import Loader from 'components/Loader';
import logo from 'assets/images/logo-nearle1.png';
import { useSelector, useDispatch } from 'react-redux';
import { OpenToast } from 'components/third-party/OpenToast';
import { closeGlobalToast, GlobalToast } from 'components/nearle_components/GlobalToast';
import Visibility from '@mui/icons-material/Visibility';
import VisibilityOff from '@mui/icons-material/VisibilityOff';
import { setLoginUser } from 'store/reducers/loginUserSlice';

const Login = () => {
  const dispatch = useDispatch();
  const fcmtoken = useSelector((state) => state.fcm);
  const permission = useSelector((state) => state.fcm.permission);
  const theme = useTheme();
  const [loading, setLoading] = useState(false);
  let navigate = useNavigate();
  const [otp, setOtp] = useState('');
  const [currentotp, setCurrentotp] = useState('');
  const [userinfo, setUserinfo] = useState({});
  const [username, setUsername] = useState('');
  const [passwordStatus, setPasswordStatus] = useState(0);
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isPassword, setIspassword] = useState(false);
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [userid, setUserid] = useState(0);

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

  const loginsend = async () => {
    setLoading(true);

    if (!username) {
      opentoast('Fill All required fields');
      setLoading(false);
      return;
    }

    try {
      const res = await axios.post(`https://jupiter.nearle.app/live/api/v1/users/console/login`, {
        authname: username,
        configid: 9, // 9 -> config id for nearle console admin
        userfcmtoken: fcmtoken?.token,
        password
      });
      // user not found
      if (res.data.code == 409 && !res.data.status) {
        OpenToast(res.data.message, 'error', 3000);
      }
      // user not activated
      else if (res.data.code == 403) {
        OpenToast(res.data.message, 'warning', 3000);
      }
      //user found, no password, setup password
      else if (res.data.code == 409 && res.data.status) {
        setPasswordStatus(1); // for password and confirm password ui
        setUserid(res.data.details.userid);
        OpenToast('User Found', 'success', 3000);
        OpenToast(res.data.message, 'success', 3000);
      }
      //user found, incorrect password
      else if (res.data.code == 401 && !res.data.status) {
        OpenToast(res.data.message, 'error', 3000);
      }
      //user found, enter password
      else if (res.data.code == 401 && res.data.status) {
        OpenToast(res.data.message, 'success', 3000);
        fetchAppLocations(res.data.userid);
        setPasswordStatus(2);
      }
      // user found, correct password
      else if (res.data.code == 200 && res.data.status) {
        OpenToast(res.data.message, 'success', 1000);
        setUserinfo(res.data.details);
        const userinfo = res.data.details;
        dispatch(setLoginUser(userinfo));
        localStorage.setItem('firstname', userinfo.firstname);
        localStorage.setItem('authname', userinfo.authname);
        localStorage.setItem('roleid', userinfo.roleid);
        localStorage.setItem('tenantid', userinfo.tenantid);
        localStorage.setItem('partnerid', userinfo.partnerid);
        localStorage.setItem('applocationid', userinfo.applocationid);
        localStorage.setItem('userid', userinfo.userid);
        localStorage.setItem('userfcmtoken', userinfo.userfcmtoken);
        fetchAppLocations(userinfo.userid);
        navigate('/nearle/dispatch');
      } else {
        OpenToast(res.data.message, 'error', 3000);
      }
    } catch (err) {
      console.error(err);
      OpenToast(err.message, 'error', 5000);
    } finally {
      setLoading(false);
    }
  };
  const loginsuccessful = () => {
    localStorage.setItem('firstname', userinfo.firstname);
    localStorage.setItem('authname', userinfo.authname);
    localStorage.setItem('roleid', userinfo.roleid);
    localStorage.setItem('tenantid', userinfo.tenantid);
    localStorage.setItem('partnerid', userinfo.partnerid);
    localStorage.setItem('applocationid', userinfo.applocationid);
    localStorage.setItem('userid', userinfo.userid);
    localStorage.setItem('userfcmtoken', userinfo.userfcmtoken);
    closeGlobalToast(); // to close the pin snackbar

    navigate('/nearle/dispatch');
  };

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

  const fetchAppLocations = async (id) => {
    const response = await axios.get(`${process.env.REACT_APP_URL}/partners/getlocations/?userid=${id}`);
    const updatedLocations = [...response.data.details, { locationname: 'All', applocationid: 0 }];
    localStorage.setItem('applocations', JSON.stringify(updatedLocations));
  };
  const updateUser = async () => {
    const response = await axios.put(`${process.env.REACT_APP_URL2}/users/update`, {
      userid,
      password
    });
    if (response.data.status) {
      OpenToast(response.data.message, 'success', 3000);
      OpenToast('Enter Password to Login', 'success', 3000);
      setPasswordStatus(2);
      setPassword('');
    }
  };

  return (
    <Box sx={{ minHeight: '100vh', display: 'flex', bgcolor: '#f8fafc' }}>
      {loading && <Loader />}

      {/* ---- Left brand panel (hidden on small screens) ---- */}
      <Box
        sx={{
          display: { xs: 'none', md: 'flex' },
          position: 'relative',
          overflow: 'hidden',
          flexBasis: '46%',
          flexDirection: 'column',
          justifyContent: 'space-between',
          color: '#fff',
          p: 6,
          background: 'linear-gradient(150deg, #4D1C61 0%, #662582 52%, #9255AB 100%)'
        }}
      >
        {/* decorative light glows */}
        <Box
          sx={{
            position: 'absolute',
            top: -120,
            right: -80,
            width: 360,
            height: 360,
            borderRadius: '50%',
            background: 'radial-gradient(circle, rgba(255,255,255,0.18) 0%, rgba(255,255,255,0) 70%)'
          }}
        />
        <Box
          sx={{
            position: 'absolute',
            bottom: -150,
            left: -110,
            width: 440,
            height: 440,
            borderRadius: '50%',
            background: 'radial-gradient(circle, rgba(255,255,255,0.12) 0%, rgba(255,255,255,0) 70%)'
          }}
        />

        <Box sx={{ position: 'relative' }}>
          <Box
            sx={{
              bgcolor: '#fff',
              borderRadius: 2,
              px: 1.5,
              py: 0.75,
              display: 'inline-flex',
              boxShadow: '0 8px 20px rgba(0,0,0,0.18)'
            }}
          >
            <img src={logo} alt="NearlExpress" style={{ height: 30, display: 'block' }} />
          </Box>
        </Box>

        <Box sx={{ position: 'relative' }}>
          <Typography sx={{ fontSize: 34, fontWeight: 700, lineHeight: 1.18, letterSpacing: '-0.02em', mb: 2 }}>
            Operate your dispatch,
            <br />
            end to end.
          </Typography>
          <Typography sx={{ fontSize: 16, color: 'rgba(255,255,255,0.82)', maxWidth: 430, lineHeight: 1.6 }}>
            Orders, AI route optimisation, live rider tracking and billing — all in the NearlExpress operator console.
          </Typography>
        </Box>

        <Stack spacing={1.25} sx={{ position: 'relative' }}>
          {['Real-time fleet visibility', 'AI-optimised dispatch routes', 'Tenant, pricing & invoice control'].map((t) => (
            <Stack key={t} direction="row" spacing={1.25} alignItems="center">
              <Box
                sx={{
                  width: 22,
                  height: 22,
                  borderRadius: '50%',
                  bgcolor: 'rgba(255,255,255,0.18)',
                  display: 'inline-flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: 13,
                  fontWeight: 700
                }}
              >
                ✓
              </Box>
              <Typography sx={{ fontSize: 14.5, color: 'rgba(255,255,255,0.9)' }}>{t}</Typography>
            </Stack>
          ))}
        </Stack>
      </Box>

      {/* ---- Right form panel ---- */}
      <Box sx={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', p: { xs: 2.5, sm: 4 } }}>
        <Box sx={{ width: '100%', maxWidth: 420 }}>
          <Card
            sx={{
              width: '100%',
              borderRadius: 3,
              border: `1px solid ${theme.palette.divider}`,
              boxShadow: '0 14px 40px rgba(15, 23, 42, 0.10)',
              p: { xs: 2.5, sm: 4 }
            }}
          >
            {/* Logo */}
            <Stack alignItems="center" mb={2.5}>
              <img src={logo} alt="loginpagelogo" style={{ maxHeight: 48 }} />
            </Stack>

            {/* Title */}
            <Typography variant="h3" textAlign="center" sx={{ fontWeight: 700, mb: 0.5 }}>
              Welcome back
            </Typography>
            <Typography variant="body2" textAlign="center" sx={{ color: '#64748b', mb: 3 }}>
              Sign in to the NearlExpress console
            </Typography>

            <CardContent sx={{ p: 0 }}>
            <form
              noValidate
              onSubmit={(e) => {
                e.preventDefault();
                if (passwordStatus == 0) {
                  loginsend();
                } else if (passwordStatus == 1) {
                  if (!password || !confirmPassword || password != confirmPassword) {
                    OpenToast('Check Password', 'warning', 3000);
                  } else {
                    updateUser();
                  }
                } else if (passwordStatus == 2) {
                  if (!password) {
                    OpenToast('Invalid Password', 'warning', 3000);
                  }
                  loginsend();
                }
                // if (currentotp) {
                //   if (currentotp == otp) {
                //     loginsuccessful();
                //     fetchAppLocations();
                //   } else {
                //     opentoast('Invalid pin');
                //   }
                // }
              }}
            >
              <Stack spacing={3}>
                {/* Email */}
                <TextField
                  autoFocus
                  fullWidth
                  label="E-mail Address"
                  variant="outlined"
                  autoComplete="email"
                  required
                  value={username}
                  onChange={(e) => setUsername(e.target.value.toLocaleLowerCase())}
                  InputProps={{ readOnly: passwordStatus }}
                />
                {/*  Setup Password  */}
                {passwordStatus == 1 && (
                  <Stack display={'flex'} flexDirection={'column'} spacing={3}>
                    <Typography variant="h4" textAlign="start" mb={3}>
                      Setup Password
                    </Typography>
                    <TextField
                      autoFocus
                      fullWidth
                      label="Enter New Password"
                      variant="outlined"
                      required
                      type={showPassword ? 'text' : 'password'}
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      InputProps={{
                        endAdornment: (
                          <InputAdornment position="end">
                            <IconButton onClick={() => setShowPassword((prev) => !prev)} edge="end">
                              {showPassword ? <VisibilityOff /> : <Visibility />}
                            </IconButton>
                          </InputAdornment>
                        )
                      }}
                    />

                    <TextField
                      error={confirmPassword !== '' && password !== confirmPassword}
                      fullWidth
                      label="Re-Enter Password"
                      variant="outlined"
                      required
                      type={showConfirmPassword ? 'text' : 'password'}
                      value={confirmPassword}
                      onChange={(e) => setConfirmPassword(e.target.value)}
                      InputProps={{
                        endAdornment: (
                          <InputAdornment position="end">
                            <IconButton onClick={() => setShowConfirmPassword((prev) => !prev)} edge="end">
                              {showConfirmPassword ? <VisibilityOff /> : <Visibility />}
                            </IconButton>
                          </InputAdornment>
                        )
                      }}
                    />
                  </Stack>
                )}
                {/* Enter Password */}
                {passwordStatus == 2 && (
                  <Stack display={'flex'} flexDirection={'column'} spacing={3}>
                    <Typography variant="h4" textAlign="start" mb={3}>
                      Enter Password
                    </Typography>
                    <TextField
                      autoFocus
                      fullWidth
                      label="Enter Password"
                      variant="outlined"
                      required
                      type={showPassword ? 'text' : 'password'}
                      value={password}
                      onChange={(e) => setPassword(e.target.value)}
                      InputProps={{
                        endAdornment: (
                          <InputAdornment position="end">
                            <IconButton onClick={() => setShowPassword((prev) => !prev)} edge="end">
                              {showPassword ? <VisibilityOff /> : <Visibility />}
                            </IconButton>
                          </InputAdornment>
                        )
                      }}
                    />
                  </Stack>
                )}

                {/* OTP */}
                {isPassword && (
                  <Stack spacing={1.5}>
                    <Stack direction="row" justifyContent="space-between">
                      <FormLabel>Enter Password</FormLabel>
                      <Link
                        variant="body2"
                        sx={{ cursor: 'pointer' }}
                        onClick={() => {
                          setOtp('');
                          loginsend();
                        }}
                      >
                        Retry
                      </Link>
                    </Stack>

                    {/* <OtpInput
                      shouldAutoFocus
                      value={otp}
                      onChange={(otp) => setOtp(otp)}
                      numInputs={4}
                      containerStyle={{ justifyContent: 'space-between' }}
                      inputStyle={{
                        width: 48,
                        height: 48,
                        borderRadius: 8,
                        border: `1px solid ${borderColor}`,
                        fontSize: 18
                      }}
                      focusStyle={{
                        outline: 'none',
                        border: `1px solid ${theme.palette.primary.main}`,
                        boxShadow: theme.customShadows.primary
                      }}
                    /> */}
                    <TextField type="passowrd" value={password} onChange={(e) => setPassword(e.target.value)} />
                  </Stack>
                )}
                {/* Submit */}
                <AnimateButton>
                  <Button fullWidth size="large" type="submit" variant="contained" color="primary">
                    Continue
                  </Button>
                </AnimateButton>
              </Stack>
            </form>
            </CardContent>
          </Card>

          {/* footer */}
          <Stack direction="row" justifyContent="center" alignItems="center" flexWrap="wrap" useFlexGap spacing={2} sx={{ mt: 3 }}>
            <Typography
              variant="caption"
              component={Link}
              href="https://nearle.in"
              target="_blank"
              sx={{ color: '#94a3b8', textDecoration: 'none', fontWeight: 600, '&:hover': { color: '#662582' } }}
            >
              &copy; All rights reserved
            </Typography>
            <Typography
              variant="caption"
              component={Link}
              href="https://nearle.in/terms"
              target="_blank"
              sx={{ color: '#94a3b8', textDecoration: 'none', fontWeight: 600, '&:hover': { color: '#662582' } }}
            >
              Terms and Conditions
            </Typography>
            <Typography
              variant="caption"
              component={Link}
              href="https://nearle.in/privacy"
              target="_blank"
              sx={{ color: '#94a3b8', textDecoration: 'none', fontWeight: 600, '&:hover': { color: '#662582' } }}
            >
              Privacy Policy
            </Typography>
          </Stack>
        </Box>
      </Box>
    </Box>
  );
};

export default Login;
