// app/print/page.jsx
"use client";
import { getToken } from "@/actions/cookies";
import fetchData from "@/api/fetch-data";
import getUserProfile from "@/api/user/getUserProfile";
import AlertWarning from "@/app/ui/shared/AlertWarning";
import FallbackImage from "@/app/ui/shared/FallbackImage";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { toastError } from "@/services/custom-toast";
import { useCurrency } from "@/stores/currency-state";
import { useSettings } from "@/stores/settings";
import { useQuery } from "@tanstack/react-query";
import { useLocale, useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import { CiCalendar } from "react-icons/ci";
import { MdPayment } from "react-icons/md";
import { PiNoteThin } from "react-icons/pi";

// BY: Mohammed Hossam
export default function PrintPage({ params: { id } }) {
  const t = useTranslations("orderDetails"); // Initialize translations
  const p = useTranslations("print"); // Initialize translations
  const m = useTranslations(); // Initialize translations
  const locale = useLocale();
  // const t = useTranslations("orderDetails"); // Initialize translations
  const [userData, setUserData] = useState(null);
  const [orderWanted, setOrderWanted] = useState(null);
  const { currencyShortname, rate } = useCurrency();
  const { setting } = useSettings();

  // Query to fetch orders data
  const { data, isLoading, error } = useQuery({
    queryKey: ["print", locale],
    queryFn: async () => {
      setUserData(await getUserProfile());
      const token = await getToken();
      if (!token) throw new Error("No token found");
      return fetchData({ endPoint: "/user/orders", locale, token });
    },
    staleTime: 1000 * 60 * 5,
  });
  useEffect(() => {
    if (data) {
      setOrderWanted(data?.data?.find((order) => order.id == id));
    }
    if (!isLoading && orderWanted && !error) {
      window.print(); // Automatically trigger the print dialog when data is ready and there's no error
    }
  }, [isLoading, error, orderWanted]);
  // if (!data) return  <AlertWarning text={m('error-message')} />;

  // Loader
  if (isLoading)
    return (
      <div className="flex items-center justify-center w-full h-[40vh]">
        <div className="loader"></div>
      </div>
    );
  // Error handling
  if (error) return toastError(m("error-message"));
  if (data?.error) return <AlertWarning text={data?.message} />;
  if (!data?.error && data?.data?.length === 0)
    return <AlertWarning text={m("error-message")} />;
  // Format date utility
  const formatDate = (dateString) => {
    const date = new Date(dateString);
    return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
  };
  return (
    <div className="container space-y-6 my-6">
      {/* START PRINT HEADER */}
      <div className="flex justify-center">
        <FallbackImage
          src={setting?.data?.images?.header}
          width={100}
          height={100}
          alt="product"
          className="object-contain  max-lg:w-10"
        />
      </div>
      {/* END PRINT HEADER */}
      {/* START TOP CARD */}
      <div className="bg-white rounded-sm p-4">
        {/* Loop through the orders array */}
        {orderWanted && (
          <div
            key={orderWanted.id}
            className="xl:space-y-5 flex items-center justify-center flex-col rounded-2xl p-5 bg-white xl:py-6"
          >
            {/* START TOP */}
            <div className="flex flex-wrap max-lg:text-center items-center gap-2 max-lg:my-2 xl:gap-5">
              <div className="flex text-md items-center gap-x-2 ">
                <CiCalendar />
                <h4>{formatDate(orderWanted?.created_at)}</h4>
              </div>
              <div className="flex text-md items-center gap-x-2 ">
                <PiNoteThin />
                <h4>
                  {t("id")} {orderWanted?.ordernumber}
                </h4>
              </div>
              <div className="flex text-md items-center gap-x-2 ">
                <MdPayment />
                <h4>{t("paymentMethod")}</h4>
              </div>
            </div>
            {/* END TOP */}
            {/*START SEPERATOR */}
            <div className="p-[.5px] w-[90%] m-auto bg-gray-200"></div>
            {/*END SEPERATOR */}
          </div>
        )}
        {/* START CENTER */}
        {userData && (
          <div className="flex flex-wrap justify-around py-5 gap-y-10">
            {/* Adjust grid based on screen size */}
            <div className="space-y-3">
              <h3 className="text-[#2E2E2E] lg:text-lg">{t("customerName")}</h3>
              <h3 className="text-[#747474] lg:text-md">
                {userData?.name} {userData?.lastname}
              </h3>
            </div>
            <div className="space-y-3">
              <h3 className="text-[#2E2E2E] lg:text-lg">{t("phoneNumber")}</h3>
              <h3 className="text-[#747474] lg:text-md">{userData?.phone}</h3>
            </div>
            <div className="space-y-3">
              <h4 className="font-bold text-xl">{t("totalAmount")}</h4>
              <h4 className="text-[#747474] text-2xl font-bold">
                {parseFloat(orderWanted?.total * rate).toFixed(2)}
                <span className="font-light">{currencyShortname}</span>
              </h4>
            </div>
          </div>
        )}
        {/* END CENTER */}
      </div>
      {/* END TOP CARD */}
      {/* START TABLE OF PRODUCTS DETAILS*/}
      {/* Order Details Table */}
      <Table>
        <TableHeader className="bg-light lg:py-10 text-white">
          <TableRow className="lg:font-extrabold">
            <TableHead className="lg:text-xl text-black">
              {t("product")}
            </TableHead>
            <TableHead className="lg:text-xl text-black">
              {t("price")}
            </TableHead>
          </TableRow>
        </TableHeader>
        <TableBody className="cursor-pointer">
          {orderWanted?.products?.map((product, index) => (
            <TableRow key={index} className="lg:text-xl lg:shadow">
              <TableCell className="flex items-center gap-3">
                <FallbackImage
                  src={product.photo || "/products/product3.png"}
                  width={50}
                  height={50}
                  alt="product"
                  className="object-contain max-lg:w-10"
                />
                <div>
                  <h4>{product.title}</h4>
                  <p className="text-sm lg:font-extrabold">
                    {product.description}
                  </p>
                </div>
              </TableCell>
              <TableCell>
                <span className="font-extrabold mx-2">
                  {parseFloat(product.price * rate)?.toFixed(2)}
                </span>
                <span>{currencyShortname}</span>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
      {/* END TABLE OF PRODUCTS DETAILS*/}
      {/* START TOTAL PRICE */}
      <div className="bg-white rounded-sm p-5 ">
        <div className=" space-y-4 lg:space-y-7">
          <div className="flex justify-between">
            <h3 className="lg:text-xl lg:font-semibold">{p("cost")}</h3>
            <p className="lg:text-xl">
              <span className="font-extrabold">
                {parseFloat(
                  (orderWanted?.total - orderWanted?.shipping_cost) * rate
                )?.toFixed(2)}
              </span>{" "}
              {currencyShortname}
            </p>
          </div>

          <div className="flex justify-between">
            <h3 className="lg:text-xl lg:font-semibold">{p("charge")}</h3>
            <p className="lg:text-xl">
              <span className="font-extrabold">
                {parseFloat(orderWanted?.shipping_cost * rate)?.toFixed(2)}
              </span>{" "}
              {currencyShortname}
            </p>
          </div>
        </div>

        <div className="p-[1px] bg-gray-200 my-5"></div>
        <div className="flex justify-between">
          <h3 className="lg:text-xl font-extrabold">{p("total")}</h3>
          <p className="lg:text-xl">
            <span className="font-extrabold">
              {parseFloat(orderWanted?.total * rate)?.toFixed(2)}
            </span>
            {currencyShortname}
          </p>
        </div>
      </div>
      {/* END TOTAL PRICE */}
      {/* START FOOTER */}
      <div className="bg-white my-10 flex p-5 flex-wrap items-center justify-between">
        <div className="flex">
          <p>&#128151;</p>
          <h4 className="font-extrabold"> {p("thanks")}</h4>
          <p>&#128151;</p>
        </div>
        <div className="flex">
          <h4>
            {p("apply")}{" "}
            <span className="font-bold">{p("termsandconditions")}</span>
          </h4>
        </div>
      </div>
      {/* END FOOTER */}
    </div>
    // <></>
  );
}
