import {
    Box,
    Center,
    HStack,
    Image,
    Input,
    Text,
    VStack,
} from "@chakra-ui/react";
import axios from "axios";
import { useState } from "react";
import { useForm } from "react-hook-form";
// import { useDispatch } from "react-redux";
import logo from "../assets/logo.svg";
import { Button } from "../components/ui/button";
import { Field } from "../components/ui/field";
import { toaster, Toaster } from "../components/ui/toaster";
import { useNavigate } from "react-router-dom";

interface FormValues {
    mobileNumber: number;
}

const ForgotPassword = () => {
    const navigate = useNavigate();
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const {
        register,
        handleSubmit,
        formState: { errors },
    } = useForm<FormValues>();

    const onSubmit = handleSubmit(async (data) => {
        const username = import.meta.env.VITE_USER_NAME || ""; // Replace with actual username
        const password = import.meta.env.VITE_PASSWORD || ""; // Replace with actual password
        const basicAuth = `${username}:${password}`; // Encode to Base64
        
        setIsLoading(true);
        try {
            const res = await axios.post(
                `${import.meta.env.VITE_API_URL}/send-otp`,
                {
                    mobile_number: Number(data.mobileNumber),
                },
                {
                    headers: {
                        Authorization: `Basic ${basicAuth}`,
                        "Content-Type": "application/json",
                    },
                }
            );

            if (res.status === 200) {
                navigate(`/forgot-password/verify?phone=${data.mobileNumber}`)
            } else {
                // alert(res.data.message || "Something went wrong");
                toaster.create({
                    // title: error?.response?.data?.message,
                    title: res.data.message || "Something went wrong",
                    type: "error",
                })
                setIsLoading(false);
            }
            console.log("============", res);

        } catch (error) {
            console.log('error', error);

            if (error) {
                toaster.create({
                    // title: error?.response?.data?.message,
                    title: "Something Went Wrong",
                    type: "info",
                })
                // console.log("Login failed", error?.response?.data?.message);
                setIsLoading(false);
            }
        }
    });

    return (

        <VStack appearance={'light'} w={"100%"} h={"100vh"} bg={"#ffffff"}>
            <HStack
                boxShadow={"rgba(99, 99, 99, 0.2) 0px 2px 8px 0px"}
                w={"100%"}
                ps={8}
                h={"7%"}
                justifyContent={"flex-start"}
            >
                <Image w={50} src={logo} />
            </HStack>

            <HStack w={"100%"} h={"93%"} p={8} gap={8}>
                <Center
                    display={{ base: "none", md: "flex" }}
                    bg={"#02A0A033"}
                    w={"50%"}
                    h={"100%"}
                    rounded={"3xl"}
                >
                    <Image w={250} src={logo} />
                </Center>

                <Box
                    as={"form"}
                    onSubmit={onSubmit}
                    p={{ base: 4, md: 16 }}
                    w={{ base: "100%", md: "50%" }}
                    h={"100%"}
                >
                    <VStack gap={2} w={"100%"}>
                        <Text
                            w={"100%"}
                            textAlign={"center"}
                            fontSize={"24px"}
                            fontWeight={"normal"}
                            color={"#313039"}
                        >
                            Forgot Password
                        </Text>

                        <Box mt={6} gap={4} w={"full"}>
                            <Field
                                color={"#313039"}
                                label={"Enter Mobile Number"}
                                w={"100%"}
                                invalid={!!errors.mobileNumber}
                                errorText={errors.mobileNumber?.message}
                                mb={4}
                            >
                                <Input
                                    type="number"
                                    ps={3}
                                    maxLength={10}
                                    {...register("mobileNumber", {
                                        required: "Please enter a 10 digit mobile number",
                                        pattern: {
                                            value: /^[0-9]{10}$/,
                                            message: "Mobile number must be exactly 10 digits"
                                        }
                                    })}
                                    placeholder="Enter Mobile Number"
                                    onInput={(e) => {
                                        const target = e.target as HTMLInputElement;
                                        target.value = target.value.replace(/\D/g, "").slice(0, 10);
                                    }}
                                />
                            </Field>
                            <Button
                                loading={isLoading}
                                mt={4}
                                size={"sm"}
                                bg={"#02A0A0"}
                                rounded={"md"}
                                w={"100%"}
                                color={"#ffffff"}
                                type="submit"
                            >
                                Send OTP
                            </Button>
                        </Box>
                    </VStack>
                </Box>
                <Toaster />
            </HStack>
        </VStack>
    );
};

export default ForgotPassword;
