import { BASE_URL } from "@/components/main/BaseUrl";
import BillboardDetailContent from "@/components/billboards/BillboardDetailContent";
import BillboardNotFound from "@/components/billboards/BillboardNotFound";
import { IAdvertising, IRate } from "@/types/types";
import { cookies } from "next/headers";
import { Metadata } from "next";
import { generatePageMetadata } from "@/utils/generatePageMetadata";
import { getLocaleBundle } from "@/lib/i18n/resources";
import { getServerLanguage } from "@/lib/i18n/server";

interface IBillboardProps {
  params: Promise<{ id: string; title: string }>;
}

async function getBillboardData(id: string, token: string) {
  const response = await fetch(`${BASE_URL}/advertising/get/web/${id}`, {
    next: { revalidate: 60 },
    headers: {
      Authorization: token ? `Bearer ${token}` : "",
    },
  });
  if (!response.ok) return null;
  return await response.json();
}

export async function generateMetadata({
  params,
}: IBillboardProps): Promise<Metadata> {
  const { id } = await params;
  const lang = await getServerLanguage();
  const token = (await cookies()).get("token")?.value || "";
  const common = getLocaleBundle(lang).common as {
    billboards: { notFoundMeta: string };
  };

  const data = await getBillboardData(id, token);
  const billboard = data?.advertising as IAdvertising;

  if (!billboard) {
    return { title: common.billboards.notFoundMeta };
  }

  const title = billboard.title || "";
  const category = billboard.category || "";
  const province = billboard.province?.name || "";
  const city = billboard.city?.name || "";
  const neighborhood = billboard.neighbourhood || "";

  const shouldHideProvince = (title.length + category.length + city.length) > 40;

  const titleParts = [
    title,
    category,
    !shouldHideProvince ? province : null,
    city,
    neighborhood !== city ? neighborhood : null,
  ].filter(Boolean);

  const dynamicTitle = titleParts.join(" - ");

  const urlSlug = titleParts
    .join(" ")
    .trim()
    .replace(/\s+/g, "-")
    .replace(/-+/g, "-");

  const address = billboard.address || `${province} ${city} ${neighborhood}`;
  const dynamicDescription = `${address} - ${billboard.description || ""}`.substring(0, 160);

  return generatePageMetadata({
    title: dynamicTitle,
    description: dynamicDescription,
    path: `/billboards/${id}/${encodeURIComponent(urlSlug)}`,
    appendSiteName: true,
    lang,
  });
}

async function BillboardPage({ params }: IBillboardProps) {
  const { id } = await params;
  const token = (await cookies()).get("token")?.value || "";

  const data = await getBillboardData(id, token);

  if (!data || !data.advertising) {
    return <BillboardNotFound />;
  }

  const billboard = data.advertising as IAdvertising;
  const rate = data.rate as IRate;

  return <BillboardDetailContent billboard={billboard} rate={rate} />;
}

export default BillboardPage;
