import { useNavigate } 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,
  Image,
  Input,
  InputGroup,
  InputLeftElement,
  InputRightElement,
  Text,
  useToast,
} from "@chakra-ui/react";
import GlobalStateContext from "../../Contexts/GlobalStateContext";
import Cookies from "js-cookie";
import ToastBox from "../../Components/ToastBox";
import { useForgotPasswordMutation, useLoginMutation } from "../../Services/token.serivce";
import * as Yup from "yup";
import { EmailIcon, PhoneIcon } from "@chakra-ui/icons";


const validationSchema = Yup.object().shape({
  emailAddress: Yup.string()
  .email("Invalid email address")
  .required("Email address is required"),
});


const ForgotPassword = () => {
  const [show, setShow] = useState(false);
  const handleClick = () => setShow(!show);
  const { isAuthenticate, setIsAuthenticate } = useContext(GlobalStateContext);
  const toast = useToast();
  
  const [isLoading, setIsLoading] = useState(false);

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

  const [forgotPassword] = useForgotPasswordMutation()

  useEffect(() => {
    if (isAuthenticate) {
      navigate("/sponser");
    }
  }, [navigate, isAuthenticate]);


  

  const onSubmit = async (value) => {
    setIsLoading(true);
    try {
      const res = await forgotPassword(value).unwrap();
      console.log(res);
      
      if (res?.statusCode === 200) {
        toast({
          render: () => (
            <ToastBox status={"success"} message={res?.message} />
          ),
        })
        setIsLoading(false);
        localStorage?.setItem("email", value?.emailAddress)
        localStorage?.setItem('code',res?.data)
        // setIsAuthenticate(true);
        // Cookies.set("isAuthenticated", true, { expires: 7 });
            navigate(`/otp-screen/${res?.data}`);
                reset();
      }else if(res?.error){
        
        toast({
          render: () => (
            <ToastBox status={"success"} message={res?.error?.message} />
          ),
        })
        setIsLoading(false);

      }

    } catch (err) {
      if (err) {
        toast({
          render: () => (
            <ToastBox status={"error"} message={err?.data?.message} />
          ),
        });
        setIsLoading(false);
      }
    }






    // if (value.emailAddress === "admin@optifii.com" && value.password_hash === "Admin@123") {
    //   return setTimeout(() => {
    //     // dispatch(loginUser(true));
    //     setIsAuthenticate(true);
    //     setIsLoading(false);
    //     toast({
    //       render: () => (
    //         <ToastBox status={"success"} message={"Login Successfully"} />
    //       ),
    //     });

    //     Cookies.set("isAuthenticated", true, { expires: 7 });
    //     navigate("/");
    //   }, 2000); // 3-second delay
    // } else {
    //   return setTimeout(() => {
    //     // dispatch(loginUser(true));
    //     setIsAuthenticate(false);
    //     setIsLoading(false);

    //     toast({
    //       render: () => (
    //         <ToastBox status={"error"} message={"Invalid credentials"} />
    //       ),
    //     });
    //     reset();
    //     navigate("/login");
    //   }, 2000);
    // }
  };

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(validationSchema),
  });

  console.log(errors);


  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={handleSubmit(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 your Email Address
          </Text>
        </Box>

        <FormControl mb={6}>
          {/* <FormLabel className="rubix-text-dark ps-1 web-text-medium fw-bold">
            E-mail <span className="text-danger">*</span>
          </FormLabel> */}

         
        <InputGroup size={'lg'}>
    <InputLeftElement display={'flex'} alignItems={'center'} pointerEvents='none'>
      <EmailIcon color='gray.300' />
    </InputLeftElement>
    <Input 
            {...register("emailAddress")}
            focusBorderColor="purple.500"
            type="text"
            name="emailAddress"
            variant="filled"
            placeholder="Email Address"
            size="lg"
            className="web-text-medium"  />
  </InputGroup>
          {errors.emailAddress && (
            <span className="text-danger web-text-small fw-bold ps-2 d-flex align-items-center gap-1 mt-1">
              <TiWarning className="fw-bold fs-5 " /> {errors.emailAddress.message}
            </span>
          )}
        </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}
        >
          Continue
        </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 ForgotPassword;
