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";
import { normalizeUserLevel, parseUserLevelFromSlug } from "@/lib/userLevel";
import { parseExpertiseFromSlug } from "@/lib/expertiseColors";

export type HomeListFilters = {
  expertise?: string;
  province?: string;
  city?: string;
  userLevel?: string;
  provinceName?: string;
  cityName?: string;
};

export function resolveHomeListFilters(
  slugSegments: string[] = [],
  filters: Omit<HomeListFilters, "provinceName" | "cityName"> & {
    rateFilter?: string;
    hashtag?: string;
  }
): HomeListFilters {
  let provinceName = "";
  let cityName = "";
  let expertise = filters.expertise || "";
  let userLevel = normalizeUserLevel(filters.userLevel || "");
  let provinceId = filters.province || "";
  let cityId = filters.city || "";

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

    const parsedExpertise = parseExpertiseFromSlug(fullText);
    if (parsedExpertise) expertise = parsedExpertise;
    else if (fullText.includes("متخصصین")) expertise = "";

    const parsedLevel = parseUserLevelFromSlug(fullText);
    if (parsedLevel) userLevel = parsedLevel;

    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 (!provinceName && !cityName) {
      const province = provinces.find((p) => p.slug === slugSegments[0]);
      if (province) {
        provinceId = province.id.toString();
        provinceName = province.name;
        if (slugSegments[1]) {
          const city = cities.find((c) => c.slug === slugSegments[1]);
          if (city) {
            cityId = city.id.toString();
            cityName = city.name;
          }
        }
      }
    }
  }

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

  return {
    expertise,
    province: provinceId,
    city: cityId,
    userLevel,
    provinceName,
    cityName,
  };
}

export function buildHomeListPath(
  filters: HomeListFilters,
  slugPath?: string
): string {
  if (slugPath) return slugPath.startsWith("/") ? slugPath : `/${slugPath}`;
  return getSeoPage("home", DEFAULT_LANGUAGE).path;
}

export function buildHomeListSeo(
  filters: HomeListFilters,
  slugPath?: string,
  lang: AppLanguage = DEFAULT_LANGUAGE
) {
  const homePage = getSeoPage("home", lang);
  const templates = getListSeoTemplates(lang).home as Record<string, string>;

  const hasFilters = Boolean(
    filters.expertise ||
      filters.city ||
      filters.province ||
      filters.userLevel ||
      filters.cityName ||
      filters.provinceName
  );

  if (!hasFilters) {
    return {
      title: homePage.title,
      description: homePage.description,
      path: homePage.path,
      h1: homePage.h1 ?? homePage.title,
    };
  }

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

  const expertisePart = filters.expertise
    ? interpolateTemplate(templates.expertisePart, {
        expertise: filters.expertise,
      })
    : templates.defaultExpertisePart;

  const levelPart = filters.userLevel
    ? interpolateTemplate(templates.levelPart, { level: filters.userLevel })
    : "";

  const titleCore = [templates.titlePrefix, expertisePart, levelPart, location]
    .filter(Boolean)
    .join(" ")
    .replace(/\s+/g, " ")
    .trim();

  const expertiseLabel =
    filters.expertise || templates.defaultExpertiseLabel;
  const locationText = location ? ` ${location}` : "";

  return {
    title: formatLocalizedSeoTitle(titleCore, lang),
    description: interpolateTemplate(templates.filteredDescription, {
      expertise: expertiseLabel,
      location: locationText,
    }),
    path: buildHomeListPath(filters, slugPath),
    h1: titleCore,
  };
}
