
import { DialogCloseTrigger, Field, IconButton, Input, Stack, Text } from "@chakra-ui/react";
import { Button } from "../../components/ui/button";
import { DialogBody, DialogContent, DialogFooter, DialogHeader, DialogRoot, DialogTitle } from "../../components/ui/dialog";
// import EnterPassword from "./EnterPassword";
import { useForm } from "react-hook-form";
import { useEffect, useState } from "react";
import { toaster, Toaster } from "../../components/ui/toaster";
import { useNewPasswordSetMutation } from "../../Redux/Service/profile.password";
import { LuEye, LuEyeOff } from "react-icons/lu";
import { InputGroup } from "../../components/ui/input-group";

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

type FormData = {
    new_password: string;
    confirm_password: string;
};

function Changepassword({ onClose, isOpen }: EnterPasswordProps) {
    const [showOldPassword, setShowOldPassword] = useState(false);
    const [showNewPassword, setShowNewPassword] = useState(false);
    const [newPasswordSet] = useNewPasswordSetMutation()
    const [isLoading, setIsLoading] = useState(false);
    const {
        register,
        handleSubmit,
        formState: { errors },
        setError,
        clearErrors,
        watch,
        reset,
    } = useForm<FormData>({
        defaultValues: {
            new_password: '',
            confirm_password: ''
        }
    });

    const newPassword = watch("new_password");
    const confirmPassword = watch("confirm_password");

    useEffect(() => {
        if (newPassword && confirmPassword && newPassword !== confirmPassword) {
            setError("confirm_password", {
                type: "manual",
                message: "Passwords do not match"
            });
        } else if (confirmPassword) {
            clearErrors("confirm_password");
        }
    }, [newPassword, confirmPassword, setError, clearErrors]);


    const onSubmit = async (data: FormData) => {

        if (data.new_password === '' || data.confirm_password === '') {
            return
        }

        if (data.new_password !== data.confirm_password) {
            setError("confirm_password", {
                type: "manual",
                message: "Passwords do not match"
            });
            return;
        }

        console.log('ERROR', errors)
        console.log('Change submitted:', data);

        clearErrors("confirm_password");

        setIsLoading(true);
        const payload = {
            new_password: data.new_password,
            confirm_password: data.confirm_password
        }

        try {
            const res = await newPasswordSet(payload).unwrap()

            if (res.status === 'success') {
                toaster.create({
                    title: "Password changed Successfully",
                    type: "success",
                });
                onClose()
            } else {
                toaster.create({
                    title: res.data.message || "Invalid password",
                    type: "error",
                });

            }
            reset()
        } catch (error: any) {
            toaster.create({
                title: error.data.message || "Something went wrong",
                type: "error",
            });
        } finally {
            setIsLoading(false);
        }
    };
    return (
        <>
            <DialogRoot
                placement="center"
                open={isOpen}
                onOpenChange={(open) => !open && onClose()}
            >

                {/* <DialogTrigger asChild>
                    <Button bg="#02A0A0" size={'2xs'} color={"#fff"} px={2}  >
                        Change Password
                    </Button>
                </DialogTrigger> */}

                <DialogContent
                    bg={"#fff"}
                    w={{ base: '90%', md: '400px' }}
                    p={2}
                    bgSize={'md'}
                >
                    <DialogHeader bg="white" pt={3} pb={2} >
                        <DialogTitle alignSelf="center" color="black" fontSize="18px" textAlign={"center"}>CHANGE PASSWORD</DialogTitle>
                    </DialogHeader>
                    <form onSubmit={handleSubmit(onSubmit)}>
                        <DialogBody bg="white" pt={5}>
                            <Stack p={2} >
                                <Field.Root>
                                    <Field.Label color="black" pt={1} fontSize="12px">New password</Field.Label>
                                    <InputGroup
                                        width={'100%'}
                                        endElement={
                                            <IconButton
                                                aria-label={showOldPassword ? "Hide password" : "Show password"}
                                                size="sm"
                                                // variant="outline"
                                                onClick={() => setShowOldPassword(!showOldPassword)}
                                                _hover={{ bg: "transparent" }}
                                                height={'fit-content'}
                                                mr={2}
                                            >
                                                {showOldPassword ? <LuEye /> : <LuEyeOff />}
                                            </IconButton>
                                        }>
                                        <Input
                                            color="black"
                                            pl={1}
                                            fontSize="12px"
                                            height="30px"
                                            type={showOldPassword ? "text" : "password"}
                                            border={errors.new_password ? "1px solid red" : "1px solid grey"}
                                            {...register("new_password", {
                                                required: "Password is required",
                                                minLength: {
                                                    value: 8,
                                                    message: "Password must be at least 8 characters",
                                                },
                                            })}
                                        />
                                    </InputGroup>
                                    {/* <IconButton
                                        aria-label={showPassword ? "Hide password" : "Show password"}
                                        size="sm"
                                        variant="ghost"
                                        onClick={() => setShowPassword(!showPassword)}
                                    >
                                        {showPassword ? <LuEye /> : <LuEyeOff />}
                                    </IconButton> */}

                                    {errors.new_password && (
                                        <Text color="red.500" fontSize="xs" mt={1}>
                                            {errors.new_password.message}
                                        </Text>
                                    )}

                                </Field.Root>
                                <Field.Root>
                                    <Field.Label color="black" pt={1} fontSize="12px">Confirm password</Field.Label>
                                    <InputGroup
                                        width={'100%'}
                                        endElement={
                                            <IconButton
                                                aria-label={showNewPassword ? "Hide password" : "Show password"}
                                                size="sm"
                                                // variant="outline"
                                                onClick={() => setShowNewPassword(!showNewPassword)}
                                                _hover={{ bg: "transparent" }}
                                                height={'fit-content'}
                                                mr={2}
                                            >
                                                {showNewPassword ? <LuEye /> : <LuEyeOff />}
                                            </IconButton>
                                        }>
                                        <Input
                                            color="black"
                                            pl={1}
                                            fontSize="12px"
                                            height="30px"
                                            type={showNewPassword ? "text" : "password"}
                                            border={errors.confirm_password ? "1px solid red" : "1px solid grey"}
                                            {...register("confirm_password", {
                                                required: "Please confirm your password",
                                                validate: (value) =>
                                                    value === newPassword || "Passwords do not match",
                                            })}
                                        />
                                    </InputGroup>

                                    {errors.confirm_password && (
                                        <Text color="red.500" fontSize="xs" mt={1}>
                                            {errors.confirm_password.message}
                                        </Text>
                                    )}
                                </Field.Root>

                            </Stack>
                        </DialogBody>
                        <DialogFooter display="flex" justifyContent="center" mt={2} p={2}
                        >
                            {/* <EnterPassword /> */}
                            <Button
                                loading={isLoading}
                                mt={6}
                                w="100%"
                                bg="#02A0A0"
                                color="white"
                                type="submit"
                            >
                                Submit
                            </Button>
                        </DialogFooter>
                    </form>
                    <DialogCloseTrigger color="black" />
                </DialogContent>
            </DialogRoot >
            <Toaster />
        </>
    )
}

export default Changepassword