import { BASE_URL } from "@/components/main/BaseUrl";
import React from "react";
import { cookies } from "next/headers";
import Container from "@/components/elements/Container";
import { IAdvertising, IRate } from "@/types/types";
import Image from "next/image";
import BillboardImageSlider from "@/components/billboards/BillboardPage/BillboardImageSlider";
import MainBillboardCardActions from "@/components/billboards/MainBillboardCard/MainBillboardCardActions";
import BillboardDetails from "@/components/billboards/BillboardPage/BillboardDetails";
import { Metadata } from "next";

import { generatePageMetadata } from "@/utils/generatePageMetadata";

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

// تابع کمکی برای دریافت اطلاعات بیلبورد جهت جلوگیری از تکرار کد در Metadata و Page
async function getBillboardData(id: string, token: string) {
  const response = await fetch(`${BASE_URL}/advertising/get/web/${id}`, {
    cache: "no-store",
    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 token = (await cookies()).get("token")?.value || "";

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

  if (!billboard) {
    return { title: "بیلبورد یافت نشد | مدستاگرام" };
  }

  // ۱. استخراج متغیرها
  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(" - ");

  // ۳. هماهنگ‌سازی URL با تایتل (تبدیل تمام اجزا به اسلاگ با خط تیره)
  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,
  });
}

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 <Container className="py-20 text-center font-bold">بیلبورد یافت نشد!</Container>;
  }

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

  return (
    <Container>
      <a
        href={`/billboards/profile/${billboard?.creatorId}/${encodeURIComponent(billboard?.title || "")}`}
      >
        <h1 className="font-bold md:text-xl text-lg text-center mt-2 line-clamp-2 mb-4 text-text-blue-light dark:text-text-blue-dark">
          {billboard?.title}
        </h1>
      </a>
      <div className="px-4 w-full text-sm md:text-md font-semibold">
        <div className="flex justify-between">
          <div className="flex gap-4">
            <a
              href={`/billboards/profile/${billboard?.creatorId}/${encodeURIComponent(billboard?.title || "")}`}
            >
              <h2 className="text-text-green-light dark:text-text-green-dark font-semibold line-clamp-2 ">
                {billboard?.category}
              </h2>
            </a>

            <div className="flex items-center justify-center">
              <>
                <span>{rate?.adTotalRatings ? rate?.adTotalRatings : "0"}</span>
                <Image
                  width={22}
                  height={22}
                  alt={"medal-star icon"}
                  src={`/images/icons/medal-star.svg`}
                  className="pb-1"
                />
              </>
            </div>
            <div className="flex items-center">
              <>
                <span>
                  {rate?.adAverageRating ? rate?.adAverageRating : "0"}
                </span>
                <Image
                  width={22}
                  height={22}
                  alt={"star icon"}
                  src={`/images/icons/star1.svg`}
                  className="pb-1"
                />
              </>
            </div>
          </div>
          {billboard?.showDiscount && billboard?.mostDiscountPercentage && (
            <div className="text-md bg-red-600 text-white w-16 h-8 flex items-center justify-center rounded-full pt-1">
              {billboard?.mostDiscountPercentage}%
            </div>
          )}
        </div>
        {billboard?.images && (
          <BillboardImageSlider images={billboard?.images} />
        )}
        <hr />
        <MainBillboardCardActions
          _id={billboard?._id}
          likedByUser={billboard?.likedByUser}
          likesCount={billboard?.likesCount}
          commentsCount={billboard?.commentsCount}
          viewCount={billboard?.viewCount}
          isDetail={true}
        />
        
        {/* بخش نمایش مکان بهبود یافته برای سئو و خوانایی */}
        <div className="flex flex-wrap gap-4 mt-6 p-4 bg-gray-50 dark:bg-zinc-900 rounded-xl">
          <div className="flex gap-1 text-gray-500">
             <span>استان:</span>
             <span className="text-black dark:text-white">{billboard?.province?.name}</span>
          </div>
          <div className="flex gap-1 text-gray-500">
             <h3>شهر:</h3>
             <span className="text-black dark:text-white">{billboard?.city?.name}</span>
          </div>
          <div className="flex gap-1 text-gray-500">
             <h4>محله:</h4>
             <span className="text-black dark:text-white">{billboard?.neighbourhood}</span>
          </div>
        </div>
        
        <div className="flex gap-2 mt-4 mb-8">
          <span className="text-gray-500">آدرس:</span>
          <h5 className="font-bold">{billboard?.address || "ثبت نشده"}</h5>
        </div>

        <BillboardDetails
          services={billboard?.services}
          features={billboard?.features}
          contactInfo={billboard?.contactInfo}
          description={billboard?.description}
          lat={billboard?.lat}
          lng={billboard?.lng}
          _id={billboard?._id}
        />
      </div>
    </Container>
  );
}

export default BillboardPage;