"use client";
import Link from "next/link";
import React, { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { ArrowRightOutlined, ArrowLeftOutlined } from "@ant-design/icons";
import { FaArrowRightLong } from "react-icons/fa6";
import { IoIosArrowBack } from "react-icons/io";
import { IoMdCopy } from "react-icons/io";
import { useSelector } from "react-redux";
import { message } from "antd";
import Image from "next/image";
import { useTranslations, useLocale } from "next-intl";
import axios from "@/utils/axios-config";

export interface DataType {
  id: number;
  status: number;
  type: number;
  value: number;
  code: string;
  start_date: string;
  end_date: string;
}
function PointsPage() {
  // ADD POINT
  const [points, setPoints] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const t = useTranslations();
  // const [message, setMessage] = useState<string>(t("points-limit"));
  // END ADD POINT
  const [discount, setDiscount] = useState<any>(undefined);
  const [showCreateCode, setShowCreateCode] = useState(true);
  const [codes, setCodes] = useState<DataType[]>([]);
  const [profileData, setProfileData] = useState<any>({});
  const [fetchCodesLoading, setFetchCodesLoading] = useState(false);
  const [copied, setCopied] = useState(false);
  const [codeId, setCodeId] = useState<number | undefined>(undefined);
  const [pointInputChanged, setPointInputChanged] = useState(false);
  const router = useRouter();
  const currentLocale = useLocale();
  const isRTL = currentLocale === "ar";
  // const { profile } = useSelector((state: { Auth: any }) => state.Auth);
  const statusObj: { [key: number]: string } = {
    1: t("active-promo-code"),
    2: t("inactive-promo-code"),
  };

  // useEffect(() => {
  //   console.log("profila dataaa", profile);
  // }, []);
  const fetchProfileData = async () => {
    try {
      const response = await axios.get("auth/profile");
      const data = response?.data?.data;
      setProfileData(data);

      console.log("profile", data);
    } catch (err: any) {}
  };
  useEffect(() => {
    fetchProfileData();
  }, []);
  const fetchCodesData = async () => {
    setFetchCodesLoading(true);
    try {
      const response = await axios.get("coupons");
      const data = response?.data?.data;
      //console.log("codes", data);
      setCodes([...data]);
      setFetchCodesLoading(false);
    } catch (err: any) {
      setFetchCodesLoading(false);
    }
  };
  useEffect(() => {
    fetchCodesData();
  }, []);

  /// copy code handler
  const handleCopy = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {}
  };

  // ADD POINT

  const handleRedeem = async () => {
    if (+points < +profileData?.redeem_points_count) {
      //setMessage(t("Please enter a valid number of points (1-500)"));
      return;
    }

    setLoading(true);
    // setMessage(t("points-limit"));

    try {
      const response = await axios.post(`/coupons/${points}`);
      //  console.log("response", response.data.data);
      // setMessage(`${t("Success! Promo Code:")} ${response.data.data}`);
      message.success(response.data.message);
      fetchCodesData();
      setShowCreateCode(false);
    } catch (error: any) {
      message.error(error?.message);
      //setMessage(t("not_valid_points"));
    } finally {
      setLoading(false);
      setDiscount(0);
      fetchCodesData();
    }
  };
  useEffect(() => {
    fetchCodesData();
  }, []);
  // END ADD POINT

  return (
    <div
      className={`container mx-auto px-4    pt-[2rem] pb-[20px] `}
      //  dir={isRTL ? "rtl" : "ltr"}
    >
      {showCreateCode ? (
        <div className="container mx-auto px-3 sm:px-0 flex flex-col justify-center py-6">
          <div className="w-[100%] sm:w-[620px] mx-auto my-6 py-6">
            <div className="border border-[#03B89E] rounded-md bg-[#DEFFFC] flex justify-center items-center w-[100%] h-[110px] p-[0px] sm:p-[15px] mb-[20px]">
              <p
                className={`text-center  border-solid border-e-[1px] border-primary w-[50%] font-[600] max-[300px]:text-[18px] max-[400px]:text-[20px] text-[22px] sm:text-[24px] text-[#03B89E] relative `}
              >
                {t("my-points")}
              </p>

              <p className="text-center w-[50%] font-[600] max-[300px]:text-[18px] max-[400px]:text-[20px] text-[22px] sm:text-[24px] text-[#184363]">
                {profileData?.count_points}
                <br />
                {t("point")}
              </p>
            </div>
            <p className="text-[16px] sm:text-[18px] font-[500] text-[#03B89E] mb-[5px]">
              {t("convert-point-into-discount")}
            </p>
            <p className="text-[14px] sm:text-[16px] font-[500] text-[#8C8C8C] mb-[20px]">
              {t("create-code-to-gain-discount-value-on-order")}
            </p>
            <div className="flex justify-start items-start mb-[25px]">
              <div className="flex-grow">
                <input
                  disabled={
                    Number(profileData?.count_points) < Number(profileData?.redeem_points_count)
                  }
                  placeholder={t("points")}
                  type="number"
                  className={`w-full !outline-none border border-primary rounded-md p-[15px]  text-[14px] sm:text-[16px]`}
                  onChange={(e: any) => {
                    setPoints(Number(e.target.value));
                    setPointInputChanged(true);
                    if (
                      Number(e.target.value) >=
                      Number(profileData?.redeem_points_count)
                    ) {
                      const discountValue = (
                        (Number(e.target.value) /
                          Number(profileData?.redeem_points_count)) *
                        Number(profileData?.redeem_points_price)
                      ).toFixed(2);
                      setDiscount(Number(discountValue));
                    } else {
                      setDiscount(0);
                    }
                  }}
                />
                {pointInputChanged &&
                  points < profileData?.redeem_points_count && (
                    <p className="text-[12px] sm:text-[14px] font-[400] text-[#FF0000] mb-[25px]">
                      <span className="text-[#FF0000] mt-2">
                        {t("points-less")}
                        {profileData?.redeem_points_count}
                      </span>
                    </p>
                  )}
              </div>

              <Image
                src={"/images/twoway-arrows.svg"}
                alt="arrow"
                width={24}
                height={18}
                className="mx-2 my-4"
              />
              <div className="flex-grow">
                <input
                  readOnly
                  value={discount}
                  placeholder={t("discount")}
                  type="text"
                  className={`!outline-none w-full border border-[#03B89E] rounded-md p-[15px]  text-[14px] sm:text-[16px]`}
                />
              </div>
            </div>

            <button
              onClick={handleRedeem}
              disabled={loading}
              className={`w-[100%] h-[56px]  ${
                points ? "!bg-primary" : "!bg-primary/50"
              } rounded-lg text-[#FBFAF3] text-[16px] sm:text-[19px] text-[700] capitalize mb-[20px] ${
                loading ? "bg-gray-400" : "bg-blue-500 hover:bg-blue-600"
              } ${points ? "cursor-pointer" : "cursor-auto"}`}
            >
              {loading ? t("Processing") : t("create-promo-code")}{" "}
              <ArrowRightOutlined
                className={isRTL ? "rotate-180 ml-[5px]" : "ml-[5px]"}
              />
            </button>
            <button
              className="text-[#03B89E] text-[16px] font-[500] capitalize text-center block w-full"
              onClick={() => {
                setShowCreateCode(false);
                fetchCodesData();
                window.scrollTo(0, 0);
              }}
            >
              {t("points-desc4")}{" "}
              <ArrowRightOutlined
                className={isRTL ? "rotate-180 ml-[5px]" : "ml-[5px]"}
              />
              {/* <FaArrowRightLong className={isRTL ? "rotate-180 ml-[5px]" : "ml-[5px]"} /> */}
            </button>
          </div>
        </div>
      ) : (
        <div>
          <div>
            <button
              className="hover:text-primary hover:bg-white border-[1px] mb-[30px] border-solid border-primary  mt-[20px] flex items-center justify-center w-fit py-1 px-2 cursor-pointer rounded-[10px] bg-primary text-white"
              onClick={() => {
                setShowCreateCode(true);
                window.scrollTo(0, 0);
              }}
            >
              <IoIosArrowBack
                className={`text-[24px] md:text-[30px] me-1 ${
                  currentLocale === "ar" ? "rotate-180" : ""
                }`}
              />{" "}
              <span className="inline-block me-2">{t("back")}</span>
            </button>
          </div>
          {codes.length > 0 ? (
            <p className="text-[18px] md:text-[20px] text-secondary font-bold py-2">
              {t("promo-codes")}
            </p>
          ) : (
            <p className="text-[18px] md:text-[20px] text-center text-secondary font-bold py-2">
              {t("no-promo-codes-found")}
            </p>
          )}
          {loading
            ? // Skeleton Loader
              [1, 2, 3, 4].map((index) => (
                <div
                  key={index}
                  className="p-4 bg-teal-100 rounded-lg animate-pulse mb-4"
                >
                  <div className="h-4 bg-gray-300 rounded w-1/3 mb-2"></div>
                  <div className="h-3 bg-gray-300 rounded w-1/2 mb-2"></div>
                  <div className="h-3 bg-gray-300 rounded w-1/4"></div>
                </div>
              )) // End Skeleton Loader
            : codes.map((item) => (
                <div
                  key={item?.id}
                  className="rounded-[10px] border-[1px] my-2 border-solid border-primary p-4 bg-custom-gradient flex justify-between"
                >
                  <div>
                    <p className="text-secondary text-[16px] py-1">
                      {item?.code}
                    </p>
                    <p className="text-[14px] text-primary py-1">
                      {statusObj[item?.status]}
                    </p>
                    <p className="inline-block text-[14px] text-gray-400 py-1">
                      {t("discount")}
                      <span className="ms-1 text-primary">
                        {item?.value} {item?.type === 1 ? t("sar") : "%"}
                      </span>
                    </p>
                    {item?.status === 1 && (
                      <p className="inline-block text-[14px] text-gray-400 py-1 mx-3">
                        {t("expired-on")}
                        <span className="ms-1 text-[#ff0000]">
                          {item?.end_date}
                        </span>
                      </p>
                    )}
                  </div>
                  <div>
                    <button
                      className="text-[14px] border-[1px] border-solid border-primary text-primary bg-white rounded-[10px] py-1 px-2"
                      onClick={() => {
                        setCodeId(item.id);
                        handleCopy(item?.code);
                      }}
                    >
                      {copied && codeId === item.id ? (
                        <p className="font-semibold">{t("copied")}</p>
                      ) : (
                        <>
                          {t("copy")}
                          <IoMdCopy className="ms-1 text-[16px] inline-block" />
                        </>
                      )}
                    </button>
                  </div>
                </div>
              ))}
        </div>
      )}
    </div>
  );
}

export default PointsPage;
