"use client";
import Image from "next/image";
import { Button, Modal, Form, Input, message } from "antd";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useTranslations, useLocale } from "next-intl";
import { useState, useEffect } from "react";
import { ArrowRightOutlined } from "@ant-design/icons";
import { RiLockPasswordFill } from "react-icons/ri";
import { useForm } from "antd/lib/form/Form";
import { useMutation } from "@tanstack/react-query";
import authActions from "@/store/auth/actions";
import {
  fetchCartLength,
  fetchFavouritesLength,
  FETCH_CART_LENGTH,
  fetchNotificationsLength,
} from "@/store/cart/actions";

import { FaEdit } from "react-icons/fa";
import { useDispatch } from "react-redux";
import axios from "@/utils/axios-config";
import { IoCall } from "react-icons/io5";
import { IoMail } from "react-icons/io5";
import { IoPerson } from "react-icons/io5";
import { removeToken } from "@/utils/cookie-config";
import loginActions from "@/store/auth/actions";
import LogoutModal from "@/components/logoutModal/LogoutModal";
import Otp from "@/components/otp";
import ProfileSkeleton from "@/components/skeletons/skeleton-profile";

function Profile() {
  const locale = useLocale();
  const [profileData, setProfileData] = useState<any>({});
  const [fetchProfileLoading, setFetchProfileLoading] = useState(false);
  const [changePhoneOpen, setChangePhoneOpen] = useState(false);
  const [deleteAccountLoading, setDeleteAccountLoading] = useState(false);
  const [deleteAccountOpen, setDeleteAccountOpen] = useState(false);
  const [showOtp, setShowOtp] = useState(false);
  const [otpTimer, setOtpTimer] = useState(false);
  const [isLogoutModal, setIsLogoutModal] = useState(false);
  const [phoneNum, setPhoneNum] = useState<any>(undefined);
  const t = useTranslations("Profile");
  const [form] = useForm();
  const dispatch = useDispatch();
  const router = useRouter();

  //// fetch profile data
  const fetchProfileData = async () => {
    setFetchProfileLoading(true);
    try {
      const response = await axios.get("auth/profile");
      const data = response?.data?.data;
      setProfileData(data);
      dispatch(authActions.profileDataAction(data));
      // console.log("profile", data);
      setFetchProfileLoading(false);
    } catch (err: any) {
      setFetchProfileLoading(false);
    }
  };
  useEffect(() => {
    fetchProfileData();
  }, []);

  const sendCode = async () => {
    try {
      const response = await axios.post("auth/send-code", {
        phone: phoneNum,
        usage: "verify",
      });
      setShowOtp(true);
      setOtpTimer(true);
    } catch (err: any) {
      message.error(err?.data?.message);
    }
  };
  //// change phone handler
  const changePhoneMutation = useMutation({
    mutationFn: (values) => axios["post"]("auth/change-phone", values),
    onSuccess: (res) => {
      message.success(res?.data?.message);
      setChangePhoneOpen(false);
      sendCode();
    },
    onError: (err) => {
      // console.log(err?.message);

      message.error(err?.message);
    },
  });
  const onFinish = (values: any) => {
    // console.log(values)
    changePhoneMutation.mutate(values);
  };

  const handleLogout = () => {
    //   const progressBar = useProgressBar(); // Manually trigger the progress bar

    // progressBar.start();
    removeToken();
    dispatch(loginActions.logout());
    setIsLogoutModal(false);
    router.push(`/${locale}/login`);
    dispatch(fetchFavouritesLength(0));
    dispatch({ type: FETCH_CART_LENGTH, payload: 0 });
    dispatch(fetchNotificationsLength(0));
  };

  const deleteAccount = async () => {
    try {
      setDeleteAccountLoading(true);
      const response = await axios.delete(`/auth/delete-account`);
      handleLogout();
      message.success(response?.data?.message);
      setDeleteAccountLoading(false);
      dispatch(fetchCartLength(0));
      dispatch(fetchFavouritesLength(0));
      dispatch(fetchNotificationsLength(0));
      setDeleteAccountOpen(false);
    } catch (error: any) {
      setDeleteAccountLoading(false);
      setDeleteAccountOpen(false);
      message.error(error?.message);
    }
  };

  if (fetchProfileLoading) {
    return (
      <div className="container   pt-[3rem] px-3 ">
        <ProfileSkeleton />
      </div>
    );
  }
  return (
    <>
      {showOtp ? (
        <div className="container mx-auto mt-[200px] w-[100%] sm:w-[620px] py-[20px] px-[10px] sm:px-[25px] border border-[#D9D9D9] rounded-lg flex flex-col justify-center items-center">
          <Otp
            phone={phoneNum}
            otpTimerStart={otpTimer}
            setOtpTimerStart={setOtpTimer}
          />
        </div>
      ) : (
        <section className="  pt-[1rem]">
          <div className="container mx-auto mt-6 px-3 flex flex-col md:flex-row justify-between items-center h-auto md:h-[490px] gap-[50px]">
            <div className="max-w-[256px] w-[50%] md:w-[30%] max-[450px]:w-[85%]">
              <div className="relative w-[200px] h-[200px] mx-auto mb-[50px]">
                <Image
                  src={profileData?.profile_image || "/images/image-8.svg"}
                  fill
                  alt="profile-img"
                  className="mb-[25px]"
                  style={{ borderRadius: "50%" }}
                  priority
                />
              </div>
              <Button
                onClick={() => router.push(`/${locale}/profile/edit-profile`)}
                className=" w-[100%] h-[52px] !bg-[#03B89E] !text-[#FFFFFF] font-[600] text-[18px] !shadow-none rounded-md mb-[20px] border !border-[#03B89E] hover:!bg-[#fff] transition-colors duration-500 hover:!text-[#03B89E]"
              >
                {/* <Link href='profile/edit-profile'>{t("edit-btn")}</Link>  */}
                {t("edit-btn")}
              </Button>
              <Button
                className=" w-[100%] h-[52px] !bg-[#fff] !text-[#03B89E] !shadow-none font-[600] text-[18px] rounded-md mb-[20px] border !border-[#03B89E] hover:!bg-[#03B89E] transition-colors duration-500 hover:!text-[#fff]"
                onClick={() => {
                  //handleLogout()
                  setIsLogoutModal(true);
                }}
              >
                {t("logout-btn")}
              </Button>
            </div>
            <div className="w-[100%] md:w-[70%] ">
              <div className="flex justify-start items-center gap-[10px]">
                <h2 className="capitalize text-[#184363] font-[600] text-[28px] min-w-[250px] mb-[30px] ">
                  {t("profile-title")}
                </h2>
                {/* <hr className=" flex-grow h-[1px] bg-[#184363] ml-4 mb-[30px] "></hr> */}
              </div>
              <ul>
                <li className="mb-[25px]">
                  <div className="flex justify-start items-center mb-[10px]">
                    <IoPerson
                      className={`text-[18px] md:text-[20px] text-primary me-1`}
                    />
                    <p className="text-[#184363] font-[400] text-[18px]">
                      {t("username")}
                    </p>
                  </div>
                  <p className="text-[#184363] font-[600] text-[18px] mx-[30px]">
                    {profileData?.name}
                  </p>
                </li>
                <li className="mb-[25px]">
                  <div className="flex justify-start items-center mb-[10px]">
                    <IoMail
                      className={`text-[18px] md:text-[20px] text-primary me-1`}
                    />
                    <p className="text-[#184363] font-[400] text-[18px]">
                      {t("email")}
                    </p>
                  </div>
                  <p className="text-[#184363] font-[600] text-[18px] mx-[30px]">
                    {profileData?.email}
                  </p>
                </li>
                <li className="mb-[25px]">
                  <div className="flex justify-start items-center mb-[10px]">
                    <IoCall
                      className={`text-[18px] md:text-[20px] text-primary me-1`}
                    />
                    <div className="flex justify-center items-center">
                      <p className="text-[#184363] font-[400] text-[18px]">
                        {t("phone")}
                      </p>

                      <p
                        className="text-[16px] md:text-[18px] cursor-pointer underline ms-[100px] md:ms-[200px] text-primary"
                        onClick={() => setChangePhoneOpen(true)}
                      >
                        {t("change-phone")}
                      </p>
                      {/* <FaEdit className="text-[20px] md:text-[24px] ms-[100px] md:ms-[200px] text-primary"/> */}
                    </div>
                  </div>

                  <p className="text-[#184363] font-[600] text-[18px] mx-[30px]">
                    {profileData?.phone}
                  </p>
                </li>
              </ul>
              <div className="flex justify-start items-center gap-[10px]">
                <Button
                  className=" min-w-[256px] h-[52px] !bg-[#FF0000] !text-[#fff]  font-[600] text-[18px] rounded-md mb-[20px] border !border-[#FF0000] hover:!bg-[#fff] transition-colors duration-500 hover:!text-[#FF0000] capitalize max-[400px]:min-w-[100%]"
                  onClick={() => {
                    setDeleteAccountOpen(true);
                  }}
                >
                  {t("del-btn")}
                </Button>
                {/* <hr className=" w-[100%] h-[1px] bg-[#184363] ml-4 mb-[30px] "></hr> */}
              </div>
            </div>
          </div>
        </section>
      )}
      <Modal
        open={changePhoneOpen}
        title={<p className="text-[20px]">{t("change-phone")}</p>}
        onCancel={() => setChangePhoneOpen(false)}
        footer={null}
      >
        <div className="py-8 ">
          <Form
            className=" flex flex-col gap-[20px] w-[410px] mx-auto 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
                  onChange={(e) => setPhoneNum(e.target.value)}
                  size="large"
                  type="number"
                  placeholder={t("new-phone-number")}
                  className="ps-[90px] "
                />
              </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={22}
                  height={22}
                />
                966+
              </div>
              {/* <IoCall
                className={`text-[20px] md:text-[25px] text-primary absolute start-4 top-1/2 -translate-y-[60%]`}
              /> */}
            </div>
            <div className="relative h-16">
              <Form.Item
                // label={<FormattedMessage id="password" />}
                name="password"
                rules={[
                  {
                    required: true,
                    message: t("password-required"),
                  },
                ]}
                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-[99999]`}
              />
            </div>
            <Button
              htmlType="submit"
              loading={changePhoneMutation.isPending}
              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`}
            >
              {t("save")}
              <ArrowRightOutlined
                className={`mx-[7px] bg-[#fff] text-[#03B89E] p-[4px] rounded-full text-[14px] transition-colors duration-300  rtl:rotate-180
                  }`}
              />
            </Button>
          </Form>
        </div>
      </Modal>
      {/*****delete account*****/}
      <Modal
        className="confirm-pickup"
        open={deleteAccountOpen}
        onCancel={() => setDeleteAccountOpen(false)}
        footer={null}
      >
        <div className="flex flex-col items-center py-8">
          <Image
            src={"/images/delete-account.png"}
            width={160}
            height={160}
            style={
              {
                // objectFit:"contain"
              }
            }
            alt="image"
          />

          <p className="font-semibold py-4 text-[16px] md:text-[20px] text-gray-700">
            {t("sure-delete-account")}
          </p>

          <Button
            loading={deleteAccountLoading}
            onClick={() => {
              deleteAccount();
            }}
            className="relative !text-white !bg-custom-red !border-none !outline-none flex justify-center items-center text-[20px] font-semibold mx-auto my-[10px] min-h-[50px] w-[70%]  !rounded-[12px]"
          >
            {t("delete-my-account")}
          </Button>
        </div>
      </Modal>

      {/***logout modal****/}
      <LogoutModal
        isVisible={isLogoutModal}
        onClose={() => setIsLogoutModal(false)}
        onConfirm={handleLogout}
      />
    </>
  );
}

export default Profile;
