"use client";

import Link from "next/link";
import { useEffect, useState } from "react";
import staticCopy from "@/i18n/staticCopy.json";
import {
  DEFAULT_LOCALE,
  getStoredLocale,
  getStoredLocaleRaw,
  LOCALE_CHANGE_EVENT,
  type LocaleCode,
} from "@/i18n/localeSwitcher";
import { localizePathnameForTag } from "@/i18n/localePathPrefix";

function collectCategoryTreePathSlugs(tree: unknown): string[] {
  const slugs: string[] = [];
  let node: unknown = tree;
  while (node && typeof node === "object" && !Array.isArray(node)) {
    const rec = node as Record<string, unknown>;
    const slug = String(rec.slug ?? "").trim();
    if (slug) slugs.push(slug);
    node = rec.sub_category ?? rec.subcategory ?? null;
  }
  return slugs;
}

function buildMarketplaceProductPath(categorySegments: string[], productSlug: string): string {
  const slug = String(productSlug ?? "").trim();
  if (!slug) return "";
  const segments = categorySegments
    .map((s) => String(s ?? "").trim())
    .filter((s) => s.length > 0 && s !== "undefined" && s !== "uncategorized");
  if (segments.length === 0) {
    return `/marketplace/${encodeURIComponent(slug)}`;
  }
  return `/marketplace/${segments.map((s) => encodeURIComponent(s)).join("/")}/${encodeURIComponent(slug)}`;
}

function hasRealCategoryPath(segments: string[]): boolean {
  return segments.some((s) => {
    const t = String(s ?? "").trim();
    return t.length > 0 && t !== "undefined" && t !== "uncategorized";
  });
}

export type Product = {
  id: number | string;
  handle: string;
  marketplace_path_segments?: string[];
  category_slug: string;
  subcategory_slug: string;
  product_slug: string;
  image: string;
  category: string;
  title: string;
  location: string;
  available_quantity: string;
  code: string;
  price_amount: string;
  currency_symbol: string;
  /** API `availability` from product-cards (e.g. "In Stock", "Recurring Supply"). */
  inStock: unknown;
  unit: string;
};

type AvailabilityBadgeStyle = {
  label: string;
  className: string;
};

/** Same rule as product detail: `currentAvailableQuantity == null || < 1` → out of stock. */
function parseAvailableQuantityFromApi(raw: string): number | null {
  const trimmed = String(raw ?? "").trim();
  if (!trimmed) return null;
  const match = trimmed.match(/-?\d+(\.\d+)?/);
  if (!match) return null;
  const n = Number(match[0]);
  return Number.isFinite(n) ? n : null;
}

function isOutOfStockFromApi(product: Pick<Product, "available_quantity">): boolean {
  const qty = parseAvailableQuantityFromApi(product.available_quantity);
  return qty === null || qty < 1;
}

function normalizeAvailabilityKey(raw: unknown): string {
  return String(raw ?? "")
    .trim()
    .toLowerCase()
    .replace(/\s+/g, " ");
}

function resolveAvailabilityBadge(
  product: Pick<Product, "inStock" | "available_quantity">,
  pc: { outOfStock: string }
): AvailabilityBadgeStyle | null {
  const value = String(product.inStock ?? "").trim();
  if (!value) {
    if (isOutOfStockFromApi(product)) {
      return {
        label: pc.outOfStock,
        className: "border-[#FF4D4D] text-[#FF4D4D]",
      };
    }
    return null;
  }

  const key = normalizeAvailabilityKey(product.inStock);

  if (key === "in stock" || key === "en stock") {
    return {
      label: value,
      className: "border-[#053F31] text-[#053F31]",
    };
  }
  if (key === "recurring supply" || key.includes("recurring") || key.includes("recurrente")) {
    return {
      label: value,
      className: "border-[#1A6BBA] text-[#1A6BBA]",
    };
  }
  if (key === "on request" || key.includes("on request") || key.includes("bajo pedido") || key === "a pedido") {
    return {
      label: value,
      className: "border-[#D97706] text-[#D97706]",
    };
  }
  if (key === "out of stock" || key.includes("out of stock") || key.includes("agotado") || key.includes("sin stock")) {
    return {
      label: value,
      className: "border-[#FF4D4D] text-[#FF4D4D]",
    };
  }

  if (isOutOfStockFromApi(product)) {
    return {
      label: value,
      className: "border-[#FF4D4D] text-[#FF4D4D]",
    };
  }

  return {
    label: value,
    className: "border-[#757575] text-[#757575]",
  };
}

export default function ProductCard({
  product,
  isLoggedIn,
}: {
  product: Product;
  isLoggedIn: boolean;
}) {
  const [uiLocale, setUiLocale] = useState<LocaleCode>(DEFAULT_LOCALE);
  useEffect(() => {
    setUiLocale(getStoredLocale());
    const onLocaleChange = () => setUiLocale(getStoredLocale());
    window.addEventListener(LOCALE_CHANGE_EVENT, onLocaleChange);
    return () => window.removeEventListener(LOCALE_CHANGE_EVENT, onLocaleChange);
  }, []);
  const pc =
    staticCopy.productCard[uiLocale as keyof typeof staticCopy.productCard] ??
    staticCopy.productCard["en-EN"];
  const availabilityBadge = resolveAvailabilityBadge(product, pc);

  const listingPathSegments = (
    Array.isArray(product.marketplace_path_segments) && product.marketplace_path_segments.length > 0
      ? product.marketplace_path_segments
      : [product.category_slug, product.subcategory_slug]
  ).map((s) => String(s ?? "").trim());

  const resolveProductHref = async (): Promise<string> => {
    const productSlug = String(product.product_slug ?? product.handle ?? "").trim();
    if (!productSlug) return "/marketplace";

    if (hasRealCategoryPath(listingPathSegments)) {
      const path = buildMarketplaceProductPath(listingPathSegments, productSlug);
      if (path) {
        return localizePathnameForTag(getStoredLocaleRaw() ?? uiLocale, path);
      }
    }

    const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
    if (base) {
      try {
        const res = await fetch(`${base}/store/product-detail/${encodeURIComponent(productSlug)}`, {
          method: "GET",
          headers: {
            "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
            "x-medusa-locale": (getStoredLocaleRaw() ?? uiLocale).trim(),
          },
          cache: "no-store",
        });
        if (res.ok) {
          const data = await res.json();
          const item = data?.product ?? data?.data ?? data;
          const treeSegments = collectCategoryTreePathSlugs(item?.category_tree);
          const path = buildMarketplaceProductPath(treeSegments, productSlug);
          if (path) {
            return localizePathnameForTag(getStoredLocaleRaw() ?? uiLocale, path);
          }
        }
      } catch {
      }
    }

    const fallback =
      buildMarketplaceProductPath(listingPathSegments, productSlug) ||
      `/marketplace/${encodeURIComponent(productSlug)}`;
    return localizePathnameForTag(getStoredLocaleRaw() ?? uiLocale, fallback);
  };

  const navigateToProduct = () => {
    if (!isLoggedIn) {
      window.location.href = "/login";
      return;
    }
    void resolveProductHref().then((href) => {
      window.location.href = href;
    });
  };

  const productSlugForHref = String(product.product_slug ?? product.handle ?? "").trim();
  const productHref = productSlugForHref
    ? localizePathnameForTag(
        getStoredLocaleRaw() ?? uiLocale,
        buildMarketplaceProductPath(listingPathSegments, productSlugForHref) ||
          `/marketplace/${encodeURIComponent(productSlugForHref)}`,
      )
    : "/marketplace";

  return (
    <div
      className="relative md:max-h-[661px] rounded-[20px] sm:rounded-[24px] md:rounded-[31px] font-outfit p-4 sm:p-5 md:p-[28px_15px_28px_20px] lg:p-[32px_15px_32px_20px] xl:p-[20px_20px_20px_20px] 2xl:p-[20px_20px_20px_20px] transition hover:bg-[#F7FAF8] group cursor-pointer"
      onClick={navigateToProduct}
      role="link"
      tabIndex={0}
      onKeyDown={(event) => {
        if (event.key === "Enter" || event.key === " ") {
          event.preventDefault();
          navigateToProduct();
        }
      }}
    >
      <span className="absolute left-0 top-[26px] h-[93%] w-[1px] bg-[#DDDDDD]" />

      <div className="mb-5 sm:mb-6 md:mb-[30px] overflow-hidden rounded-[12px] sm:rounded-[14px] md:rounded-[16px]">
        {isLoggedIn && (
          <div className="absolute left-0 top-[33px] z-10 flex items-center">
            {(() => {
              const priceRaw = String(product.price_amount ?? "").trim();
              if (!priceRaw) return null;
              const priceNum = parseFloat(priceRaw.replace(/[^\d.-]/g, ""));
              const isZeroPrice = !Number.isNaN(priceNum) && priceNum === 0;
              return (
                <>
                  <span className="absolute top-[20px] left-[8px] h-0 w-0 border-b-[14px] border-t-[14px] border-r-[12px] border-b-transparent border-t-transparent border-r-[#001F17]" />
                  <span className="absolute top-[33px] left-[8px] rounded-r-[14px] bg-[#053F31] p-[7px_18px] text-[20px] font-medium font-outfit text-[#FFFFFF]">
                    {isZeroPrice ? pc.priceToConsult : `${product.currency_symbol}${product.price_amount}/${product.unit}`}
                  </span>
                </>
              );
            })()}
          </div>
        )}

        <img
          src={product.image || undefined}
          alt={product.title}
          className="h-[200px] sm:h-[210px] md:h-[220px] lg:h-[230px] xl:h-[230px] w-full rounded-[12px] sm:rounded-[14px] md:rounded-[16px] object-cover transition-transform duration-300 ease-out group-hover:scale-105"
        />
      </div>

      <div className="h-[56px] mb-3">
        <div className="flex items-stretch justify-between gap-5">
          {product.category && <span className="min-w-0 rounded-[10px] border border-[#053F31]/20 bg-[#DAE6DC] px-[12px] py-[3px] text-[14px] font-outfit font-semibold uppercase text-[#053F31] px-md-[15px]" style={{
            display: "-webkit-box",
            WebkitLineClamp: 2,
            WebkitBoxOrient: "vertical",
            overflow: "hidden",
          }}>
            {product.category}
          </span>}

          {isLoggedIn && availabilityBadge && (
            <span
              className={`shrink-0 self-stretch whitespace-nowrap flex items-center justify-center rounded-[10px] border px-[12px] py-[3px] text-[14px] font-semibold font-outfit px-md-[15px] ${availabilityBadge.className}`}
            >
              {availabilityBadge.label}
            </span>
          )}
        </div>
      </div>

      <span className="text-[19px] mb-[10px] min-h-[20px] lg:min-h-[26px] max-w-[350px] font-outfit font-semibold text-black line-clamp-1">
        {product.title}
      </span>

      <div className="min-h-[97px] mb-[15px] space-y-2 text-[20px]">
        <div className="flex min-w-0 gap-2">
          {product.location && <p className="min-w-0 font-light text-black line-clamp-1">Location : <span className="font-light text-[#757575]">{product.location}</span></p>}
        </div>
        <div className="flex gap-2">
          {product.available_quantity && <><p className="font-light text-black">Quantity :</p>
          <p className="font-light text-[#757575]">{product.available_quantity}</p></>}
        </div>
        <div className="flex gap-2">
          {product.code && <><p className="font-light text-black">Code :</p>
          <p className="font-light text-[#757575]">{product.code}</p></>}
        </div>
      </div>

      <hr className="mb-[15px] max-w-[250px] border-[#DDDDDD]" />

      {isLoggedIn ? (
        <div className="flex flex-wrap items-center gap-4">
          <Link
            href={productHref}
            className="font-regular text-[18px] underline"
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
              navigateToProduct();
            }}
          >
            See details
          </Link>
        </div>
      ) : (
        <Link
          href="/login"
          className="font-regular text-[18px] md:underline text-[#333333]"
        >
          Log in for more details
        </Link>
      )}
    </div>
  );
}
