import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { Suspense } from "react";

import Breadcrumbs from "@/components/admin/Breadcrumbs";
import { getMerchantPageDataServer } from "@/services/coupon.service.server";

import "../../../styles/deal-style.css";
import "../../../styles/shopping-guide-style.css";

import CouponStoreClient from "./CouponStoreClient";

export const dynamic = "force-dynamic";

type Props = {
  params: Promise<{ store: string }>;
  searchParams: Promise<{ is_extension?: string }>;
};

function toReadableCategoryLabel(value: string): string {
  return decodeURIComponent(value)
    .replace(/-/g, " ")
    .replace(/\b\w/g, (char) => char.toUpperCase());
}

function formatMerchantLabel(store: string): string {
  return store
    .replace(/^https?:\/\//, "")
    .replace(/^www\./, "")
    .split("/")[0]
    .split(".")[0]
    .replace(/-/g, " ")
    .replace(/\b\w/g, (char) => char.toUpperCase());
}

function extractCategoryInfo(merchantData: any): {
  label?: string;
  href?: string;
} {
  const labelCandidate =
    merchantData?.category_name ||
    merchantData?.category ||
    merchantData?.category_title ||
    merchantData?.parent_category ||
    "";

  const label =
    typeof labelCandidate === "string" && labelCandidate.trim()
      ? toReadableCategoryLabel(labelCandidate.trim())
      : undefined;

  const slugCandidate =
    merchantData?.category_slug ||
    merchantData?.category_url ||
    merchantData?.category_path ||
    "";

  if (typeof slugCandidate !== "string" || !slugCandidate.trim()) {
    return { label };
  }

  const slug = slugCandidate.trim();

  if (slug.startsWith("/")) {
    return { label, href: slug };
  }

  if (/^https?:\/\//i.test(slug)) {
    try {
      const url = new URL(slug);
      return { label, href: url.pathname + url.search };
    } catch {
      return { label };
    }
  }

  return {
    label,
    href: `/category_coupons/${encodeURIComponent(slug)}`,
  };
}

export default async function CouponStorePage({ params, searchParams }: Props) {
  const { store = "amazon.com" } = await params;
  const { is_extension } = await searchParams;

  const cookieStore = await cookies();
  const token = cookieStore.get("token")?.value;

  const merchantPageData = await getMerchantPageDataServer(store, token);
  if (merchantPageData?.success === false) {
    redirect("/stores");
  }

  const categoryInfo = extractCategoryInfo(merchantPageData);
  const merchantLabel = formatMerchantLabel(store);

  // EXTENSION REDIRECT LOGIC
  if (is_extension === "1") {
    const redirectUrl = merchantPageData?.redirect_link || `https://${store}`;
    redirect(redirectUrl);
  }

  const breadcrumbItems: { label: string; href?: string }[] = [
    { label: "Home", href: "/" },
  ];

  if (categoryInfo?.label) {
    breadcrumbItems.push({
      label: categoryInfo.label,
      href: categoryInfo.href,
    });
  }

  breadcrumbItems.push({ label: merchantLabel });

  return (
    <>
      <div className="pt-5 pt-lg-0 bg-light ">
        <Breadcrumbs id="coupon" items={breadcrumbItems} />
      </div>

      <Suspense fallback={<div className="text-center py-5">Loading...</div>}>
        <CouponStoreClient merchantData={merchantPageData} store={store} />
      </Suspense>
    </>
  );
}
