import { useNavigate, useParams } from "react-router-dom";
import Input01 from "../../Components/Inputs/Input01";
import { useDispatch, useSelector } from "react-redux";
import { loginUser } from "../../Redux/Slice/auth";
import { useContext, useEffect, useState } from "react";
import Button01 from "../../Components/Buttons/PrimaryButton";
import { yupResolver } from "@hookform/resolvers/yup";
import { useForm } from "react-hook-form";
import { TiWarning } from "react-icons/ti";
import Loader01 from "../../Components/Loaders/Loader01";
import Asset1 from "../../assets/loginpat.png";
import logo from "../../assets/optifii_white.svg";
import {
  Box,
  Button,
  FormControl,
  FormLabel,
  HStack,
  Image,
  Input,
  InputGroup,
  InputLeftElement,
  InputRightElement,
  PinInput,
  PinInputField,
  Text,
  useToast,
} from "@chakra-ui/react";
import GlobalStateContext from "../../Contexts/GlobalStateContext";
import Cookies from "js-cookie";
import ToastBox from "../../Components/ToastBox";
import {
  useForgotPasswordMutation,
  useLoginMutation,
  useResendOtpMutation,
  useResetPasswordMutation,
} from "../../Services/token.serivce";
import * as Yup from "yup";
import { EmailIcon, PhoneIcon } from "@chakra-ui/icons";

const OtpScreen = () => {
    const params = useParams()
  const [show, setShow] = useState(false);
  const handleClick = () => setShow(!show);
  const { isAuthenticate, setIsAuthenticate } = useContext(GlobalStateContext);
  const toast = useToast();

  const [pin, setPin] = useState(""); // State to store pin value

  // Handle pin change
  const handlePinChange = (value) => {
    setPin(value);
  };

  console.log(pin);

  const [isLoading, setIsLoading] = useState(false);

  const navigate = useNavigate();
  const dispatch = useDispatch();

  const [resendPassword] = useResendOtpMutation();

  useEffect(() => {
    if (isAuthenticate) {
      navigate("/sponser");
    }
  }, [navigate, isAuthenticate]);
  
  const onSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true);
  
    if (params?.id) {
      // 3-second delay before navigating to "/reset-password"
      setTimeout(() => {
        navigate("/reset-password");
        setIsLoading(false);
      }, 3000);
    } else {
      // 3-second delay before setting authentication, setting cookies, and navigating
      setTimeout(() => {
        setIsAuthenticate(true);
        setIsLoading(false);
        Cookies.set("isAuthenticated", true, { expires: 7 });
        navigate("/");
        reset();
      }, 3000);
    }
  };


  const handleResendOtp = async () => {





  try {
    const res = await resendPassword().unwrap();
    console.log(res);
    if (res?.statusCode === 200) {
      toast({
        render: () => (
          <ToastBox status={"success"} message={res?.message} />
        ),
      })
          
    }else if(res?.error){
      toast({
        render: () => (
          <ToastBox status={"success"} message={res?.error?.message} />
        ),
      })
    }
  } catch (err) {
    if (err) {
      toast({
        render: () => (
          <ToastBox status={"error"} message={err?.data?.message} />
        ),
      });
      setIsLoading(false);
    }
  }
    
  }
  





  return (
    <Box
      h={"100vh"}
      w={"100%"}
      display={"flex"}
      justifyContent={"end"}
      overflow={"hidden"}
      // bg={'#EFEFEF'}
      bgGradient="linear(to-l, #3725EA, #5E0FCD)"
    >
      <Box
        position={"relative"}
        display={"flex"}
        justifyContent={"center"}
        alignItems={"center"}
        w={"55%"}
      >
        <Image w={48} src={logo} />
      </Box>
      <Box
        as="form"
        onSubmit={onSubmit}
        w={"45%"}
        backgroundColor={"#fff"}
        p={20}
        boxShadow={"md"}
        zIndex={2}
        display={"flex"}
        justifyContent={"center"}
        alignItems={"start"}
        flexDirection={"column"}
        position={"relative"}
        shadow={"lg"}
      >
        <Box display={"flex"} flexDirection={"column"} gap={0} mb={8}>
          <Text as={"span"} fontSize={"xl"} fontWeight={600}>
            Forgot Password
          </Text>
          <Text as={"span"} fontSize={"sm"} fontWeight={400} color={"gray.500"}>
            Enter OTP send to {localStorage?.getItem("email")}
          </Text>
        </Box>

        <FormControl mb={6}>

          <HStack justifyContent={"center"}>
            <PinInput
              value={pin}
              onChange={handlePinChange}
              size="md"
              type="alphanumeric"
              mask

            >
              <PinInputField mx={1} />
              <PinInputField mx={1}  />
              <PinInputField mx={1}  />
              <PinInputField mx={1}  />
              <PinInputField  mx={1} />
              <PinInputField  mx={1} />
            </PinInput>
          </HStack>


          
          <HStack mt={2} fontWeight={600}  fontSize={'xs'} justify={'end'} w={'100%'}>
            {/* <Text>Resend Otp</Text> */}
            <Text onClick={handleResendOtp} cursor={'pointer'}>Resend Otp</Text>
          </HStack>
        </FormControl>

        <Button
          isLoading={isLoading}
          type="submit"
          className="w-100"
          color={"whitesmoke"}
          bg="#5E0FCD"
          _hover={{ bg: "#5E0FCD", opacity: 0.9 }}
          _active={{ bg: "#5E0FCD", opacity: 1 }}
          size="md"
          fontWeight={400}
          fontSize={"sm"}
          mb={4}
        >
          Verify
        </Button>
        {/* <PrimaryButton type="submit" title={'Sent OTP'} w="100%"/> */}

        {/* <Text onClick={()=> navigate('/forgot-password')} w={'100%'} color={'gray.500'} fontSize={'sm'} textAlign={'center'} >Forgot Password</Text> */}

        <Text
          style={{
            position: "absolute",
            left: 0,
            bottom: "0%",
            fontSize: "13px",
            color: "#919191",
            textAlign: "center",
            width: "100%",
            zIndex: 2,
          }}
        >
          Optifii v1.0.0
        </Text>
      </Box>

      <Image
        style={{
          position: "absolute",
          left: 0,
          bottom: 0,
          width: 350,
        }}
        src={Asset1}
        alt="bg-img"
      />
    </Box>
  );
};

export default OtpScreen;
