import {
    Box,
    Center,
    HStack,
    Image,
    Input,
    Text,
    VStack,
} from "@chakra-ui/react";
import axios from "axios";
import { useEffect, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import logo from "../assets/logo.svg";
import { Button } from "../components/ui/button";
import { toaster, Toaster } from "../components/ui/toaster";

const VerifyOTP = () => {
    const [otp, setOtp] = useState<string[]>(["", "", "", ""]);
    const [isLoading, setIsLoading] = useState(false);
    const [timer, setTimer] = useState(60);
    const [isResendDisabled, setIsResendDisabled] = useState(true);
    const navigate = useNavigate();
    const location = useLocation();
    const queryParams = new URLSearchParams(location.search);
    const phoneNumber = queryParams.get("phone");

    useEffect(() => {
        let interval: NodeJS.Timeout;

        if (timer > 0 && isResendDisabled) {
            interval = setInterval(() => {
                setTimer((prevTimer) => prevTimer - 1);
            }, 1000);
        } else if (timer === 0) {
            setIsResendDisabled(false);
        }

        return () => clearInterval(interval);
    }, [timer, isResendDisabled]);


    const handleResendOTP = async () => {
        setIsResendDisabled(true);
        setTimer(60); // Reset timer to 1 minute

        try {
            const res = await axios.post(`${import.meta.env.VITE_API_URL}/send-otp`, {
                mobile_number: phoneNumber,
            });

            if (res.status === 200) {
                toaster.create({
                    title: "OTP resent successfully",
                    type: "success",
                });
            } else {
                toaster.create({
                    title: res.data.message || "Failed to resend OTP",
                    type: "error",
                });
                setIsResendDisabled(false); // Enable button if failed
            }
        } catch (error: any) {
            toaster.create({
                title: error.response?.data?.message || "Failed to resend OTP",
                type: "error",
            });
            setIsResendDisabled(false); // Enable button if error
        }
    };

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>, index: number): void => {
        const value = e.target.value;

        // Prevent non-numeric input
        if (/[^0-9]/.test(value)) return;

        // Update the OTP state with the new value
        const newOtp = [...otp];
        newOtp[index] = value;
        setOtp(newOtp);

        // Move focus to the next input automatically
        if (value && index < otp.length - 1) {
            const nextInput = document.getElementById(`otp-input-${index + 1}`) as HTMLInputElement;
            if (nextInput) nextInput.focus();
        }
    };

    const handleOtpSubmit = async () => {
        if (otp.length !== 4) {
            toaster.create({
                title: "OTP must be 4 digits",
                type: "error",
            });
            return;
        }

        const fullOtp = otp.join('');

        setIsLoading(true);
        try {
            const res = await axios.post(`${import.meta.env.VITE_API_URL}/verify-otp`, {
                mobile_number: phoneNumber,
                otp: fullOtp,
            });

            if (res.status === 200) {
                toaster.create({
                    title: "OTP Verified Successfully",
                    type: "success",
                });
                const userid = res.data.data.id;
                navigate(`/forgot-password/reset-password?id=${userid}`);
            } else {
                toaster.create({
                    title: res.data.message || "Invalid OTP",
                    type: "error",
                });
            }
        } catch (error: any) {
            toaster.create({
                title: error.response?.data?.message || "Something went wrong",
                type: "error",
            });
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <VStack 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>

            <Center w="100%" h="93%" p={8}>
                <Box p={8} borderWidth={1} borderRadius="lg" boxShadow="lg">
                    <Text fontSize="24px" fontWeight="bold" color="#313039" textAlign="center">
                        Enter OTP
                    </Text>

                    <Text fontSize="14px" color="gray.600" textAlign="center" mt={2}>
                        OTP sent to {phoneNumber}
                    </Text>

                    <HStack gap={4} mt={6} justify="center">
                        {otp.map((digit, index) => (
                            <Input
                                key={index}
                                id={`otp-input-${index}`}
                                value={digit}
                                maxW="50px"
                                color={"black"}
                                textAlign="center"
                                fontSize="20px"
                                placeholder="0"
                                border="1px solid grey"
                                onChange={(e) => handleChange(e, index)}
                                maxLength={1} // Only allows 1 character per input
                            />
                        ))}
                    </HStack>
                    {/* <Box textAlign="center">
                        <Text
                            color="#4746F4"
                            textDecoration="underline"
                            fontWeight="bold"
                            mt={3}
                            cursor="pointer"
                            display="inline-block"
                            px={2}
                        >
                            Resend OTP
                        </Text>
                    </Box> */}
                    <Box textAlign="center" mt={4}>
                        {isResendDisabled ? (
                            <Text color="gray.500">
                                Resend OTP in {timer} seconds
                            </Text>
                        ) : (
                            <Text
                                color="#4746F4"
                                textDecoration="underline"
                                fontWeight="bold"
                                cursor="pointer"
                                onClick={handleResendOTP}
                            >
                                Resend OTP
                            </Text>
                        )}
                    </Box>

                    <Button
                        loading={isLoading}
                        mt={6}
                        w="100%"
                        bg="#02A0A0"
                        color="white"
                        onClick={handleOtpSubmit}
                    >
                        Verify OTP
                    </Button>
                </Box>
            </Center>

            <Toaster />
        </VStack>
    );
};

export default VerifyOTP;
