"use client";
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 { useQuery } from "@tanstack/react-query";
import { useLocale, useTranslations } from "next-intl";
import Link from "next/link";
import { useEffect, useState } from "react";
import { CiCalendar } from "react-icons/ci";
import { GoArrowRight } from "react-icons/go";
import { MdPayment } from "react-icons/md";
import { PiNoteThin } from "react-icons/pi";

export default function Page({ params: { id } }) {
  const locale = useLocale();
  const t = useTranslations("orderDetails"); // Initialize translations
  const p = useTranslations("print"); // Initialize translations
  const [userData, setUserData] = useState([]);
  const [orderWanted, setOrderWanted] = useState([]);
  const { currencyShortname, rate } = useCurrency();

  // Query to fetch orders data
  const { data, isLoading, error } = useQuery({
    queryKey: ["orders", locale],
    queryFn: async () => {
      return fetchData({ endPoint: "/user/orders", locale });
    },
    staleTime: 1000 * 60 * 5,
  });

  // Find specific order in the data
  useEffect(() => {
    setUserData();
    // User function to get the data of user from token
    // START USER
    async function user() {
      setUserData(await getUserProfile());
    }
    // END USER
    user();

    if (data) {
      setOrderWanted(data?.data?.find((order) => order.id == id));
    }
  }, [id, locale, data]);

  // 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 <p>{data?.message}</p>;
  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()}`;
  };

  // Navigate to print page

  return (
    <div className="space-y-10 my-5 container">
      {/* Render each order */}
      <div className="xl:space-y-5 divide-y rounded-2xl p-5 2xl:px-14 bg-white xl:py-6">
        <div className="flex flex-wrap items-center gap-2 xl:gap-5">
          <div className="flex items-center gap-x-2 text-md">
            <CiCalendar />
            <h4>{formatDate(orderWanted?.created_at)}</h4>
          </div>
          <div className="flex items-center gap-x-2 text-md">
            <PiNoteThin />
            <h4>
              {t("id")} {orderWanted?.ordernumber}
            </h4>
          </div>
          <div className="flex items-center gap-x-2 text-md">
            <MdPayment />
            <h4>{t("paymentMethod")}</h4>
          </div>
          <span className="p-2 ms-auto rounded-sm bg-[#EBE19E]">
            {orderWanted?.status}
          </span>
        </div>
        {/* User */}
        <div className="flex flex-wrap justify-start py-5 gap-y-4 lg:gap-y-10">
          <div className="w-1/2 md:w-1/4 lg: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="w-1/2 md:w-1/4 lg: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>

        <div className="flex justify-between pt-5">
          <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>

      {/* 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">
              {p("count")}
            </TableHead>
            <TableHead className="lg:text-xl text-black">
              {t("price")}
            </TableHead>
            {/* <TableHead className="lg:text-xl text-black">{t('vatValue')}</TableHead> */}
            <TableHead className="lg:text-xl text-black">
              {t("total")}
            </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">{product.count}</span>
              </TableCell>
              <TableCell>
                <span>{currencyShortname}</span>
                <span className="font-extrabold mx-2">
                  {parseFloat(product.price * rate).toFixed(2)}
                </span>
              </TableCell>
              <TableCell>
                <Link href="#" className="font-extrabold text-[#353535]">
                  <span className="mx-2">
                    <span>{currencyShortname}</span>
                    {(
                      Number(product?.total_price?.replace(",", "")) * rate
                    ).toFixed(2)}
                  </span>
                  {/* {currencyShortname} */}
                </Link>
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
      {/* 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">
                {orderWanted.shipping_cost
                  ? 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 */}
      {/* Print Button */}
      <Link
        href={`/print/${id}`}
        className="flex items-center justify-center lg:w-1/4 md:w-1/2 mx-auto btn btn-btnColor gap-2"
      >
        <GoArrowRight className="text-xl" />
        {t("print")}
      </Link>
    </div>
  );
}
