"use client";
import { useRef } from "react";
import EmptyOrders from "./EmptyOrders";
import { Orders } from "@/interfaces/types";
import { usePathname } from "next/navigation";
import { updateURLParams } from "@/utils/helpers";
import AppPagination from "@/shared/Pagination/AppPagination";
import { useRouter } from "nextjs-toploader/app";
import { useTranslations } from "next-intl";
import MediaWithFallback from "@/shared/MediaWithFallback";
import { RS } from "@/shared/Icons";

type Props = {
  type: string;
  orders: Orders[];
  paggination: any;
  current_page: number;
};

export default function OrdersIndex({
  type,
  orders,
  paggination,
  current_page,
}: Props) {
  const t = useTranslations();
  const types = [
    { label: t("status.all"), value: "all" },
    { label: t("status.processing"), value: "processing" },
    { label: t("status.completed"), value: "completed" },
  ];
  const router = useRouter();
  const pathname = usePathname();
  const containerRef = useRef<HTMLDivElement | null>(null);

  const handlePaggination = (selectedPage: any) => {
    updateURLParams({
      params: { page: selectedPage },
      router: router,
      pathname: pathname,
    });
    setTimeout(() => {
      if (containerRef.current) {
        containerRef.current.scrollIntoView({
          behavior: "smooth",
          block: "start",
        });
      }
    }, 300);
  };
  return (
    <div className="container max-w-6xl" ref={containerRef}>
      <h1 className="text-3xl md:text-4xl mb-8">{t("NAV.orders")}</h1>
      <div className="flex gap-2 mb-8 overflow-x-auto">
        {types?.map((ele, index) => {
          return (
            <button
              key={index}
              onClick={() => {
                updateURLParams({
                  params: { type: ele?.value },
                  router,
                  pathname,
                  page: true,
                });
              }}
              className={`px-6 py-2 rounded-lg whitespace-nowrap transition-all duration-300 ${
                type === ele?.value
                  ? "bg-primary text-white"
                  : "bg-white border border-gray-200 hover:bg-gray-50"
              }`}
            >
              {ele?.label}
            </button>
          );
        })}
      </div>
      {orders?.length > 0 ? (
        <div className="space-y-4">
          {orders?.map((order, index: number) => (
            <div
              key={order?.id || index}
              className="border border-gray-200 rounded-2xl shadow-md shadow-black/10 bg-white p-6"
            >
              <div className="flex flex-wrap items-start justify-between gap-4 mb-6 pb-6 border-b border-gray-200">
                <div>
                  <div className="flex items-center gap-3 mb-2">
                    <h3 className="text-lg font-semibold">
                      {t("LABELS.order_number")} #{order?.order_number}
                    </h3>
                    <span
                      className={`statuses px-3 py-1 rounded-full text-xs font-medium statuses ${order?.status}`}
                    >
                      {t(`status.${order?.status}`)}
                    </span>
                  </div>
                  <div className="flex items-center gap-2 text-sm text-text-secondary">
                    <svg
                      xmlns="http://www.w3.org/2000/svg"
                      width="16"
                      height="16"
                      viewBox="0 0 24 24"
                      fill="none"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      className="lucide lucide-calendar"
                    >
                      <path d="M8 2v4"></path>
                      <path d="M16 2v4"></path>
                      <rect width="18" height="18" x="3" y="4" rx="2"></rect>
                      <path d="M3 10h18"></path>
                    </svg>
                    <span>{order?.arrive_date_time}</span>
                  </div>
                </div>
                <div className="text-left">
                  <p className="text-2xl text-primary flex items-center gap-1">
                    {order?.total_price} <RS className="*:fill-primary" />
                  </p>
                </div>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
                {order?.items?.map((item, itemIndex: number) => (
                  <div key={item?.id || itemIndex} className="flex gap-3">
                    <MediaWithFallback
                      src={item?.product?.image}
                      alt={item?.product?.name || "منتج"}
                      className="w-20 h-20 object-cover rounded-lg flex-shrink-0"
                    />
                    <div className="flex-1 min-w-0">
                      <p className="line-clamp-1 mb-1 font-medium">
                        {item?.product?.name}
                      </p>
                      <p className="text-sm text-text-secondary mb-1 line-clamp-2">
                        {item?.product?.description}
                      </p>
                      <div className="flex items-center justify-between">
                        <span className="text-xs text-text-secondary">
                          {t("validations.Quantity")}: {item?.amount}
                        </span>
                        <span className="text-sm text-primary font-medium flex items-center gap-1">
                          {item?.total_price} <RS className="*:fill-primary" />
                        </span>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
              <div className="grid grid-cols-1 md:grid-cols-[1.6fr_2fr] gap-4 p-4 bg-gray-50 rounded-lg">
                <div className="flex items-start gap-2">
                  <svg
                    xmlns="http://www.w3.org/2000/svg"
                    width="18"
                    height="18"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    className="lucide lucide-map-pin text-primary mt-1 flex-shrink-0"
                  >
                    <path d="M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"></path>
                    <circle cx="12" cy="10" r="3"></circle>
                  </svg>
                  <div>
                    <p className="text-sm text-text-secondary mb-1">
                      {t("Text.delivery_address")}
                    </p>
                    <p className="text-sm">
                      {order?.address?.location?.country?.name},{" "}
                      {order?.address?.location?.city?.name},{" "}
                      {order?.address?.location?.district?.name}
                    </p>
                    {order?.address?.description && (
                      <p className="text-xs text-text-secondary mt-1">
                        {order?.address?.description}
                      </p>
                    )}
                  </div>
                </div>
                <div className="grid lg:grid-cols-2 gap-6">
                  <div className="flex items-center justify-between py-2 border-b border-gray-100">
                    <div className="flex items-center gap-2">
                      <div className="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center">
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          width="14"
                          height="14"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          className="text-gray-600"
                        >
                          <path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path>
                        </svg>
                      </div>
                      <span className="text-sm text-gray-600">
                        {t("Text.subtotal")}
                      </span>
                    </div>
                    <span className="text-sm font-medium flex items-center gap-1">
                      {order?.price}
                      <RS className="*:fill-gray-600" />
                    </span>
                  </div>

                  <div className="flex items-center justify-between py-2 border-b border-gray-100">
                    <div className="flex items-center gap-2">
                      <div className="w-8 h-8 rounded-full bg-blue-50 flex items-center justify-center">
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          width="14"
                          height="14"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          className="text-blue-600"
                        >
                          <rect
                            width="18"
                            height="11"
                            x="3"
                            y="11"
                            rx="2"
                            ry="2"
                          ></rect>
                          <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                        </svg>
                      </div>
                      <span className="text-sm text-gray-600">
                        {t("Text.shipping")}
                      </span>
                    </div>
                    <span className="text-sm font-medium flex items-center gap-1">
                      {order?.shipping_price} <RS className="*:fill-blue-600" />
                    </span>
                  </div>

                  <div className="flex items-center justify-between py-2 border-b border-gray-100">
                    <div className="flex items-center gap-2">
                      <div className="w-8 h-8 rounded-full bg-green-50 flex items-center justify-center">
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          width="14"
                          height="14"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          className="text-green-600"
                        >
                          <circle cx="12" cy="12" r="10"></circle>
                          <path d="M12 6v6l4 2"></path>
                        </svg>
                      </div>
                      <span className="text-sm text-gray-600">
                        {t("Text.orderTax")}
                      </span>
                    </div>
                    <span className="text-sm font-medium flex items-center gap-1">
                      {order?.tax_amount} <RS className="*:fill-green-600" />
                    </span>
                  </div>

                  <div className="flex items-center justify-between py-2 border-b border-gray-100">
                    <div className="flex items-center gap-2">
                      <div className="w-8 h-8 rounded-full bg-primary flex items-center justify-center">
                        <svg
                          xmlns="http://www.w3.org/2000/svg"
                          width="14"
                          height="14"
                          viewBox="0 0 24 24"
                          fill="none"
                          stroke="currentColor"
                          strokeWidth="2"
                          strokeLinecap="round"
                          strokeLinejoin="round"
                          className="text-white"
                        >
                          <path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path>
                        </svg>
                      </div>
                      <span className="text-sm text-primary">
                        {t("Text.total")}
                      </span>
                    </div>
                    <span className="text-sm font-medium text-primary flex items-center gap-1">
                      {order?.total_price} <RS className="*:fill-primary" />
                    </span>
                  </div>
                </div>
              </div>
              {order?.occasion && (
                <div className="mt-4 p-4 bg-blue-50 rounded-lg">
                  <p className="text-sm text-text-secondary mb-1">
                    {t("LABELS.occasion")}
                  </p>
                  <p className="text-sm font-medium">{order?.occasion}</p>
                </div>
              )}
              {order?.notes && (
                <div className="mt-4 p-4 bg-primary/10 rounded-lg">
                  <p className="text-sm text-text-secondary mb-1">
                    {t("LABELS.notes")}
                  </p>
                  <p className="text-sm">{order?.notes?.replace(/\+/g, " ")}</p>
                </div>
              )}
            </div>
          ))}
        </div>
      ) : (
        <EmptyOrders />
      )}

      {orders && orders?.length > 0 && (
        <div className="py-8">
          <AppPagination
            itemsPerPage={paggination?.per_page}
            totalItems={paggination?.total}
            totalPage={paggination?.last_page}
            currentPage={+current_page}
            paginate={handlePaggination}
          />
        </div>
      )}
    </div>
  );
}
