"use client";
import fetchData from "@/api/fetch-data";
import AlertWarning from "@/app/ui/shared/AlertWarning";
import BlackBtn from "@/app/ui/shared/BlackBtn";
import { toastError } from "@/services/custom-toast";
import { useCurrency } from "@/stores/currency-state";
import { useQuery } from "@tanstack/react-query";
import { useLocale, useTranslations } from "next-intl";
import Link from "next/link";
import { CiCalendar } from "react-icons/ci";
import { MdPayment } from "react-icons/md";
import { PiNoteThin } from "react-icons/pi";

export default function Page() {
  const locale = useLocale();
  const t = useTranslations("user");
  const e = useTranslations();
  const { currencyShortname, rate } = useCurrency();
  // USE QUERY FETCH DATA OF THE USER PROFILE ACCEPT =>TOKEN  AND FETCH METHOD CASHE DATA FOR 5 Min
  const { data, isLoading, error } = useQuery({
    queryKey: ["orders", locale],
    queryFn: async () => {
      return fetchData({ endPoint: "/user/orders", locale });
    },
    staleTime: 1000 * 60 * 5,
  });

  // LOADER
  if (isLoading)
    return (
      <div className=" flex items-center justify-center  w-[100%] h-[40vh]">
        <div className="loader"></div>
      </div>
    );
  // ERROR
  if (error)
    return <AlertWarning title={error.message || e("error-message")} />;
  if (data?.error) return toastError(data?.message);
  if (!data?.error && data?.data === null)
    return <AlertWarning text={data?.message} />;

  const formatDate = (dateString) => {
    const date = new Date(dateString);
    return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
  };

  return (
    <section>
      <div className=" ">
        <div className="space-y-5">
          {/* Loop through the orders array */}
          {data?.data?.map((order) => (
            <div
              key={order?.id}
              className="xl:space-y-5 rounded-2xl p-5 bg-white xl:py-6"
            >
              {/* START TOP */}
              <div className="flex max-md:mb-4 max-md:flex-col max-lg:text-center items-center gap-2 max-lg:justify-between justify-between  max-lg:my-2 xl:gap-5">
                <div className="flex max-md:flex-col flex-wrap max-lg:text-start lg:items-center gap-2  max-lg:my-2 xl:gap-5">
                  <div className="flex text-md items-center gap-x-2 ">
                    <CiCalendar className="text-xl" />
                    <h4>{formatDate(order?.created_at)}</h4>
                  </div>
                  <div className="flex text-md items-center gap-x-2 ">
                    <PiNoteThin className="text-xl" />
                    <h4># ID {order?.id}</h4>
                  </div>
                  <div className="flex text-md items-center gap-x-2 ">
                    <MdPayment className="text-xl" />
                    <h4>{order?.paymentMethod}</h4>
                  </div>
                </div>
                {/* Navigate to the dynamic route with order id */}
                <Link href={`/order-details/${order?.id}`}>
                  <BlackBtn className={"ms-auto "} title={t("moredetails")} />
                </Link>
              </div>
              {/* END TOP */}
              {/*START SEPERATOR */}
              <div className="p-[.5px]  m-auto bg-gray-200"></div>
              {/*END SEPERATOR */}
              {/* START BOTTOM */}
              <div className="flex flex-wrap max-lg:gap-4 justify-between max-lg:my-2">
                {/* RIGHT SIDE */}
                <div className="flex max-md:flex-col max-md:m-auto  items-center ">
                  <div className="flex max-md:flex-col max-md:me-auto  lg:items-center   gap-2 2xl:gap-20 lg:text-center">
                    <div className="max-md:flex items-center gap-1">
                      <h4 className="lg:mb-2 xl:mb-4">
                        {t("countofproducts")}
                      </h4>
                      <span className="text-[#747474] text-lg font-extrabold">
                        {order?.products?.length}
                      </span>
                    </div>
                    <div className="max-md:flex items-center gap-1">
                      <h4 className="lg:mb-2 xl:mb-4">{t("status")}</h4>
                      <span className="p-2 rounded-sm bg-[#EBE19E]">
                        {order?.status}
                      </span>
                    </div>
                  </div>
                </div>
                {/* LEFT SIDE */}
                <div className="flex max-md:m-auto gap-x-5 2xl:gap-x-20 items-center xl:me-10 flex-wrap text-center">
                  <div className="flex max-md:flex-col gap-3 2xl:gap-x-20  lg:items-center">
                    <h4 className="font-bold text-xl">{t("total")}</h4>
                    <h4 className="text-[#747474] text-2xl font-extrabold">
                      <span className="font-light mx-1">
                        {parseFloat(order?.total * rate).toFixed(2)}
                      </span>
                      <span>{currencyShortname}</span>
                    </h4>
                  </div>
                </div>
              </div>
              {/* END BOTTOM */}
            </div>
          ))}
          {/* END CARD */}
        </div>
      </div>
    </section>
  );
}
