import { DialogBody, DialogCloseTrigger, DialogContent, DialogFooter, DialogHeader, DialogRoot, DialogTitle } from "../../components/ui/dialog"
import { Box, Input, Stack, Text } from "@chakra-ui/react"
import { Button } from "../../components/ui/button";
import { useEffect, useState } from "react";
// import { BiSolidEdit } from "react-icons/bi";
import { Toaster, toaster } from "../../components/ui/toaster";
import { useGetProfileQuery, useResendOtpMutation, useVerifyOTPMutation } from "../../Redux/Service/profile.password";
import { useForm } from "react-hook-form";
import Changepassword from "./ChangePassword";

type EnterOTPProps = {
    onClose: () => void;
    isOpen: boolean;
};

type FormData = {
    otp: string[];
};


function EnterOTP({ onClose, isOpen }: EnterOTPProps) {
    const [isLoading, setIsLoading] = useState(false);
    const [timer, setTimer] = useState(60);
    const [isResendDisabled, setIsResendDisabled] = useState(true);
    const [verifyOTP] = useVerifyOTPMutation()
    const [otpSuccess, setOtpSuccess] = useState(false);
    const [resendOtp] = useResendOtpMutation()
    const { data } = useGetProfileQuery()
    const id = data?.data.id


    const {
        register,
        handleSubmit,
        formState: { errors },
        reset,
    } = useForm<FormData>({
        defaultValues: {
            otp: ["", "", "", ""] // Initialize with empty strings for each digit
        }
    });

    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 resendOtp({ mobile_number: Number(id) }).unwrap()

            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
        }
    };

    // Handle change for OTP inputs
    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);

        if (value && index < 3) {
            const nextInput = document.getElementById(`otp-input-${index + 1}`) as HTMLInputElement;
            if (nextInput) nextInput.focus();
        }

        // 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();
        // }

        if (value === "" && index > 0) {
            const prevInput = document.getElementById(`otp-input-${index - 1}`) as HTMLInputElement;
            if (prevInput) prevInput.focus();
        }
    };


    const onSubmit = async (data: FormData) => {
        console.log('ERROR', errors)
        if (data.otp.length !== 4) {
            toaster.create({
                title: "OTP must be 4 digits",
                type: "error",
            });
            return;
        }

        const fullOtp = data.otp.join('');
        console.log('OTP submitted:', fullOtp);

        setIsLoading(true);
        try {
            const res = await verifyOTP({ otp: fullOtp }).unwrap()

            if (res.status === 'success') {
                toaster.create({
                    title: "OTP Verified Successfully",
                    type: "success",
                });
                setOtpSuccess(true);
                reset();
            } else {
                toaster.create({
                    title: res.data.message || "Invalid OTP",
                    type: "error",
                });
            }
            reset()
        } catch (error: any) {
            toaster.create({
                title: error.data?.message || "Something went wrong",
                type: "error",
            });
            setOtpSuccess(false);
        } finally {
            setIsLoading(false);
        }
    };

    return (
        <>
            <DialogRoot placement="center"
                open={isOpen}
                onOpenChange={(open) => !open && onClose()}>
                {/* <DialogTrigger asChild>
                    <Button w="100%" bg="#02A0A0" color={"#fff"}>
                        Submit
                    </Button>

                </DialogTrigger> */}

                <DialogContent
                    bg={"#fff"}
                    // w={{ lg: "60%", md: "230px" }}
                    w={{ base: '90%', md: '400px' }}

                    // height={'80vh'}
                    // overflow={'scroll'}
                    p={2} // Reduced padding
                    bgSize={'md'}
                >
                    <DialogHeader bg="white" pt={3} alignSelf="center">
                        <DialogTitle alignSelf="center" color="black" fontSize="18px" textAlign={"center"}>ENTER OTP</DialogTitle>
                    </DialogHeader>
                    <form onSubmit={handleSubmit(onSubmit)}>
                        <DialogBody bg="white" pt={2}>
                            <Text color={"black"} textAlign={"center"}>OTP has been sent successfully</Text>
                            {/* <Box display="flex" flexDirection="row" alignItems="center" justifyContent="center" p={3}>
                            <BiSolidEdit color="black" />
                            <Text color="black" textAlign="center" ml={2}>9619565889</Text>
                        </Box> */}


                            <Stack direction="row" justify="center" pt={2}>

                                {/* 4 OTP Inputs */}
                                {Array.from({ length: 4 }).map((_, index) => (
                                    <Input
                                        key={index}
                                        id={`otp-input-${index}`}
                                        maxW="50px"
                                        color="black"
                                        textAlign="center"
                                        fontSize="20px"
                                        placeholder="0"
                                        border={errors.otp?.[index] ? "1px solid red" : "1px solid grey"}
                                        maxLength={1}
                                        {...register(`otp.${index}`, {
                                            required: "Digit required",
                                            pattern: {
                                                value: /^[0-9]$/,
                                                message: "Must be a single digit"
                                            },
                                            onChange: (e) => handleChange(e, index)
                                        })}
                                    />
                                ))}
                            </Stack>
                            <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>

                        </DialogBody>
                        <DialogFooter display="flex" justifyContent="center" mt={2} p={2}
                        >
                            <Button
                                loading={isLoading}
                                mt={6}
                                w="100%"
                                bg="#02A0A0"
                                color="white"
                                type="submit"
                            >
                                Verify OTP
                            </Button>
                        </DialogFooter>
                    </form>
                    <DialogCloseTrigger color="black" />
                </DialogContent>
            </DialogRoot >
            {otpSuccess && (<Changepassword
                onClose={() => {
                    setOtpSuccess(false);
                    onClose()
                }}
                isOpen={otpSuccess}
            />)}
            <Toaster />
        </>
    )
}

export default EnterOTP