"use client";
import { useForm } from "antd/lib/form/Form";
import { useMutation } from "@tanstack/react-query";
import axios from "../../../utils/axios-config";
import Image from "next/image";
import { Form, Button, message, Input, Modal } from "antd";
import { ArrowRightOutlined } from "@ant-design/icons";
import Link from "next/link";
import { useTranslations, useLocale } from "next-intl";
import { useDispatch } from "react-redux";
import { IoCall } from "react-icons/io5";
import { useState } from "react";
import Otp from "@/components/otp";
import { RiLockPasswordFill } from "react-icons/ri";
import { GiConfirmed } from "react-icons/gi";
import loginActions from "@/store/auth/actions";
import { removeToken } from "@/utils/cookie-config";

function ForgetPasswordPage() {
  const [pagesParts, setPageParts] = useState("send-phone");
  const [otpTimerStart, setOtpTimerStart] = useState(false);
  const [successModalOpen, setSuccessModalOpen] = useState(false);
  const [otp, setOtp] = useState<any>(undefined);
  const [phoneNum, setPhoneNum] = useState<any>(undefined);
  const t = useTranslations("ForgetPassword");
  const locale = useLocale();
  const isRTL = locale === "ar";
  const [form] = useForm();
  const dispatch = useDispatch();

  /// send code

  const sendCode = useMutation({
    mutationFn: (values) => axios["post"]("auth/send-code", values),
    onSuccess: (res) => {
      // sendCode();
      setPageParts("otp");
      setOtpTimerStart(true);
    },
    onError: (err) => {
      message.error(err?.message);
    },
  });
  const onFinish = (values: any) => {
    values.usage = "forget_password";
    //console.log(values)
    sendCode.mutate(values);
  };

  //// new password handler
  const newPassMutation = useMutation({
    mutationFn: (values) => axios["post"]("auth/forget-password", values),
    onSuccess: (res) => {
      removeToken();
      dispatch(loginActions.logout());
      setSuccessModalOpen(true);
    },
    onError: (err) => {
      console.log(err?.message);

      message.error(err?.message);
    },
  });
  const onNewPassFinish = (values: any) => {
    values.code = otp;
    values.phone = phoneNum;

    newPassMutation.mutate(values);
  };
  return (
    <>
      <section
        className={`pt-[180px] pb-[20px] ${isRTL ? "text-right" : "text-left"}`}
        dir={isRTL ? "rtl" : "ltr"}
      >
        <div className="container mx-auto px-3 sm:px-0 flex flex-col justify-center items-center">
          {pagesParts === "send-phone" && (
            <div className="w-[100%] sm:w-[620px] py-[50px] px-[10px] sm:px-[25px] border border-[#D9D9D9] rounded-lg flex flex-col justify-center items-center">
              <h2 className="text-[#03B89E] text-[30px] sm:text-[45px] font-[700] mb-[15px] text-center">
                {t("forget-password-title")}
              </h2>
              <p className="text-[#8C8C8C] text-[13px] sm:text-[16px] font-[600] mb-[30px] text-center w-[410px] max-[460px]:w-full">
                {t("forget-password-title-desc")}
              </p>
              <Form
                className=" flex flex-col gap-[20px] w-[410px] max-[460px]:w-full"
                layout="vertical"
                form={form}
                //initialValues={{ remember: true }}
                onFinish={onFinish}
                autoComplete="off"
              >
                <div className="relative h-16">
                  <Form.Item
                    // label={<FormattedMessage id="email" />}
                    name="phone"
                    rules={[
                      {
                        required: true,
                        message: t("phone-required"),
                      },
                      {
                                            pattern: /^(05\d{8}|5\d{8})$/,
                                            message: t("phone-invalid"),
                                          },
                    ]}
                  >
                    <Input
                      size="large"
                      placeholder={t("phone-number")}
                      type="number"
                      className="ps-[90px] "
                      onChange={(e) => setPhoneNum(e.target.value)}
                    />
                  </Form.Item>
                   <div className="flex px-1  gap-2 text-gray-500 absolute start-4 top-1/2 -translate-y-[60%] border-e-[1px] border-gray-500">
                  {/* <img src="/images/ksa.svg" className="w-[20px] h-[20px]" /> */}
                  <Image
                    src="/images/ksa.svg"
                    alt="Saudi Arabia Flag"
                    width={20}
                    height={20} />
                  966+
                </div>
                </div>

                <Button
                  htmlType="submit"
                  loading={sendCode.isPending}
                  className={`${locale === "ar" ? "w-[280px]" : "w-[262px]"} max-[460px]:w-full mx-auto h-[50px] sm:h-[56px] !bg-[#03B89E] !text-white rounded-md text-[20px] sm:text-[22px] font-[600] flex items-center justify-center border !border-[#03B89E] hover:bg-[#fff] hover:text-[#03B89E] transition-colors duration-500 group`}
                >
                  {t("forget-password-btn")}
                  <ArrowRightOutlined
                    className={`mx-[7px] !bg-[#fff] !text-[#03B89E] p-[4px] rounded-full text-[14px] transition-colors duration-300  ${
                      isRTL ? "rotate-180" : ""
                    }`}
                  />
                </Button>
              </Form>
            </div>
          )}
          {pagesParts === "otp" && (
            <div className="w-[100%] sm:w-[620px] py-[50px] px-[10px] sm:px-[25px] border border-[#D9D9D9] rounded-lg flex flex-col justify-center items-center">
              <Otp
                phone={phoneNum}
                otpTimerStart={otpTimerStart}
                setOtp={setOtp}
                setOtpTimerStart={setOtpTimerStart}
                setPageParts={setPageParts}
              />
            </div>
          )}
          {pagesParts === "new-pass" && (
            <div className="w-[100%] sm:w-[620px] py-[50px] px-[10px] sm:px-[25px] border border-[#D9D9D9] rounded-lg flex flex-col justify-center items-center">
              <h2 className="text-[#03B89E] text-[30px] sm:text-[45px] font-[700] mb-[15px] text-center">
                {t("set-new-password")}
              </h2>
              <p className="text-[#8C8C8C] text-[13px] sm:text-[16px] font-[600] mb-[30px] text-center w-[410px] max-[460px]:w-full">
                {t("write-new-pass-to-account")}
              </p>
              <Form
                className=" flex flex-col gap-[20px] w-[410px] max-[460px]:w-full"
                layout="vertical"
                form={form}
                //initialValues={{ remember: true }}
                onFinish={onNewPassFinish}
                autoComplete="off"
              >
                <div className="relative h-16">
                  <Form.Item
                    // label={<FormattedMessage id="password" />}
                    name="new_password"
                    rules={[
                      {
                        required: true,
                        message: t("password-required"),
                      },
                      {
                        pattern: /^.{8,}$/,
                        message: t("new-password-invalid"),
                      },
                    ]}
                    className="!mb-0"
                  >
                    <Input.Password
                      size="large"
                      placeholder={t("password")}
                      className="ps-[45px]"
                    />
                  </Form.Item>
                  <RiLockPasswordFill
                    className={`text-[20px] md:text-[25px] !text-primary absolute start-4 top-1/2 -translate-y-[60%] z-20`}
                  />
                </div>
                <div className="relative h-16">
                  <Form.Item
                    // label={<FormattedMessage id="password" />}
                    name="new_password_confirmation"
                    rules={[
                      {
                        required: true,
                        message: t("confirmation-password-required"),
                      },
                      {
                        pattern: /^.{8,}$/,
                        message: t("new-password-invalid"),
                      },
                    ]}
                    className="!mb-0"
                  >
                    <Input.Password
                      size="large"
                      placeholder={t("confirm-password")}
                      className="ps-[45px]"
                    />
                  </Form.Item>
                  <RiLockPasswordFill
                    className={`text-[20px] md:text-[25px] text-primary absolute start-4 top-1/2 -translate-y-[60%] z-20`}
                  />
                </div>

                <Button
                  htmlType="submit"
                  loading={newPassMutation.isPending}
                  className={`${locale==='ar' ? "w-[280px]" : "w-[262px]"}  max-[460px]:w-full mx-auto h-[50px] sm:h-[56px] !bg-[#03B89E] !text-white rounded-md text-[20px] sm:text-[22px] font-[600] flex items-center justify-center border !border-[#03B89E] hover:bg-[#fff] hover:text-[#03B89E] transition-colors duration-500 group`}
                >
                  {t("forget-password-btn")}
                  <ArrowRightOutlined
                    className={`mx-[7px] !bg-[#fff] !text-[#03B89E] p-[4px] rounded-full text-[14px] transition-colors duration-300  ${
                      isRTL ? "rotate-180" : ""
                    }`}
                  />
                </Button>
              </Form>
            </div>
          )}
        </div>
      </section>
      {/*****browse modal**** */}
      <Modal open={successModalOpen} closable={false} footer={null}>
        <div className="py-8 flex flex-col items-center">
          <GiConfirmed className="text-[40px] md:text-[100px] text-primary" />
          <p className="font-bold pt-8 pb-6 text-[20px]  md:text-[30px] text-primary">
            {t("successfully-done")}
          </p>
          <Button
            className={`w-[200px] mx-auto h-[50px] sm:h-[56px] !border-none !outline-none !text-white !bg-[#03B89E]  rounded-md text-[20px] sm:text-[24px] font-[600] flex items-center justify-center border  transition-colors duration-500 group`}
          >
            <Link href={`/${locale}/login`} locale={false}>
              {t("go-to-login")}
              <ArrowRightOutlined
                className={`mx-[7px] bg-[#fff] text-[#03B89E] p-[4px] rounded-full text-[14px] transition-colors duration-300   
                  rtl:rotate-180
                `}
              />
            </Link>
          </Button>
        </div>
      </Modal>
    </>
  );
}

export default ForgetPasswordPage;
