import {
  buildLocalizedLocationLabel,
  formatLocalizedSeoTitle,
  getListSeoTemplates,
  getSeoPage,
  interpolateTemplate,
} from "@/lib/i18n/seo";
import { DEFAULT_LANGUAGE, type AppLanguage } from "@/lib/i18n/registry";
import provinces from "@/data/provinces.json";
import cities from "@/data/cities.json";

export type BillboardsListFilters = {
  province?: string;
  city?: string;
  category?: string;
  search?: string;
  sort?: string;
};

export function resolveBillboardSeoData(
  slugSegments: string[] = [],
  filters: BillboardsListFilters
) {
  let provinceId = filters.province || "";
  let cityId = filters.city || "";
  let category = filters.category || "";
  let provinceName = "";
  let cityName = "";

  if (slugSegments.length > 0) {
    const fullText = decodeURIComponent(slugSegments[0]).replace(/-/g, " ");

    if (fullText.startsWith("تبلیغات")) {
      const afterAds = fullText.split("تبلیغات")[1]?.trim();
      if (afterAds) {
        category = afterAds.split("در")[0]?.trim();
        if (category.includes("خدمات مد و زیبایی")) category = "";
      }

      if (fullText.includes("در شهر")) {
        const cityLabel = fullText.split("در شهر")[1]?.trim();
        const foundCity = cities.find((c) => cityLabel?.includes(c.name));
        if (foundCity) {
          cityId = foundCity.id.toString();
          cityName = foundCity.name;
        }
      } else if (fullText.includes("در استان")) {
        const provinceLabel = fullText.split("در استان")[1]?.trim();
        const foundProvince = provinces.find((p) =>
          provinceLabel?.includes(p.name)
        );
        if (foundProvince) {
          provinceId = foundProvince.id.toString();
          provinceName = foundProvince.name;
        }
      }
    }
  }

  if (!cityName && filters.city) {
    const city = cities.find((c) => c.id.toString() === filters.city);
    if (city) {
      cityId = city.id.toString();
      cityName = city.name;
    }
  } else if (!provinceName && filters.province) {
    const province = provinces.find((p) => p.id.toString() === filters.province);
    if (province) {
      provinceId = province.id.toString();
      provinceName = province.name;
    }
  }

  const defaultCategory =
    (getListSeoTemplates(DEFAULT_LANGUAGE).billboards as Record<string, string>)
      .defaultCategory;
  const categoryLabel = category || filters.category || defaultCategory;

  return {
    provinceId,
    cityId,
    category,
    categoryLabel,
    provinceName,
    cityName,
  };
}

export function buildBillboardsListSeo(
  slugSegments: string[] = [],
  filters: BillboardsListFilters,
  lang: AppLanguage = DEFAULT_LANGUAGE
) {
  const billboardsPage = getSeoPage("billboards", lang);
  const templates = getListSeoTemplates(lang).billboards as Record<
    string,
    string
  >;

  const hasFilters = Boolean(
    slugSegments.length ||
      filters.province ||
      filters.city ||
      filters.category ||
      filters.search ||
      filters.sort
  );

  if (!hasFilters) {
    return {
      title: billboardsPage.title,
      description: billboardsPage.description,
      path: billboardsPage.path,
      h1: billboardsPage.h1 ?? billboardsPage.title,
      ...resolveBillboardSeoData(slugSegments, filters),
    };
  }

  const data = resolveBillboardSeoData(slugSegments, filters);
  const location = buildLocalizedLocationLabel(
    {
      cityName: data.cityName,
      provinceName: data.provinceName,
    },
    lang
  );

  const titleCore = interpolateTemplate(templates.titleCore, {
    category: data.categoryLabel,
  });
  const fullTitleCore = [titleCore, location].filter(Boolean).join(" ").trim();

  const path =
    slugSegments.length > 0
      ? `/billboards/${slugSegments.join("/")}`
      : billboardsPage.path;

  const locationText = location ? ` ${location}` : "";

  return {
    ...data,
    title: formatLocalizedSeoTitle(fullTitleCore, lang),
    description: interpolateTemplate(templates.filteredDescription, {
      category: data.categoryLabel,
      location: locationText,
    }),
    path,
    h1: `${fullTitleCore}${templates.h1Suffix}`,
  };
}
