import type { Property } from "@/data/types";

export const priceRanges = [
  { label: "Всички", min: 0, max: Number.POSITIVE_INFINITY },
  { label: "До EUR 100 000", min: 0, max: 100000 },
  { label: "EUR 100 000 - EUR 300 000", min: 100000, max: 300000 },
  { label: "EUR 300 000 - EUR 500 000", min: 300000, max: 500000 },
  { label: "EUR 500 000 - EUR 1 000 000", min: 500000, max: 1000000 },
  { label: "Над EUR 1 000 000", min: 1000000, max: Number.POSITIVE_INFINITY },
] as const;

export const areaRanges = [
  { label: "Площ", min: 0, max: Number.POSITIVE_INFINITY },
  { label: "До 50 кв.м.", min: 0, max: 50 },
  { label: "50 - 100 кв.м.", min: 50, max: 100 },
  { label: "100 - 200 кв.м.", min: 100, max: 200 },
  { label: "200 - 500 кв.м.", min: 200, max: 500 },
  { label: "Над 500 кв.м.", min: 500, max: Number.POSITIVE_INFINITY },
] as const;

export const sortOptions = [
  { value: "newest", label: "Най-нови" },
  { value: "price-asc", label: "Цена ↑" },
  { value: "price-desc", label: "Цена ↓" },
  { value: "area-desc", label: "Площ ↓" },
] as const;

export type PropertiesFilters = {
  areaRange: number;
  dealType: "all" | "sale" | "rent";
  priceRange: number;
  propType: string;
  region: string;
  sortBy: (typeof sortOptions)[number]["value"];
  viewMode: "grid" | "list";
};

export type PropertySearchFilters = PropertiesFilters & {
  search: string;
};

const dealTypes = new Set(["all", "sale", "rent"] as const);
const sortValues = new Set(sortOptions.map((option) => option.value));

function pickFirst(value: string | string[] | undefined) {
  return Array.isArray(value) ? value[0] : value;
}

function clampIndex(value: string | undefined, maxIndex: number) {
  const parsed = Number(value);
  return Number.isInteger(parsed) && parsed >= 0 && parsed <= maxIndex ? parsed : 0;
}

export function getPropertiesFilters(
  searchParams: Record<string, string | string[] | undefined>,
): PropertiesFilters {
  const dealTypeInput = pickFirst(searchParams.deal);
  const propTypeInput = pickFirst(searchParams.type);
  const regionInput = pickFirst(searchParams.region);
  const sortByInput = pickFirst(searchParams.sort);
  const viewInput = pickFirst(searchParams.view);

  return {
    areaRange: clampIndex(pickFirst(searchParams.areaRange), areaRanges.length - 1),
    dealType: dealTypes.has(dealTypeInput as PropertiesFilters["dealType"])
      ? (dealTypeInput as PropertiesFilters["dealType"])
      : "all",
    priceRange: clampIndex(pickFirst(searchParams.priceRange), priceRanges.length - 1),
    propType: propTypeInput?.trim() || "all",
    region: regionInput?.trim() || "all",
    sortBy: sortValues.has(sortByInput as PropertiesFilters["sortBy"])
      ? (sortByInput as PropertiesFilters["sortBy"])
      : "newest",
    viewMode: viewInput === "list" ? "list" : "grid",
  };
}

export function getPropertySearchFilters(
  searchParams: Record<string, string | string[] | undefined>,
): PropertySearchFilters {
  return {
    ...getPropertiesFilters(searchParams),
    search: pickFirst(searchParams.search)?.trim() || "",
  };
}

export function getPropertiesSeoCopy(filters: PropertiesFilters) {
  const dealLabel =
    filters.dealType === "sale"
      ? "за продажба"
      : filters.dealType === "rent"
        ? "под наем"
        : "";

  const regionLabel = filters.region !== "all" ? ` в ${filters.region}` : " в Гърция";
  const typeLabel = filters.propType !== "all" ? `${filters.propType.toLowerCase()} ` : "имоти ";
  const title = `${typeLabel}${dealLabel}`.trim();

  return {
    heading:
      filters.dealType === "all" && filters.propType === "all" && filters.region === "all"
        ? "Имоти в Гърция"
        : `${filters.propType !== "all" ? `${filters.propType} ` : "Имоти "}${dealLabel}${regionLabel}`.replace(
            /\s+/g,
            " ",
          ).trim(),
    title:
      title === ""
        ? `Имоти${regionLabel}`
        : `${title.charAt(0).toUpperCase()}${title.slice(1)}${regionLabel}`,
    description: `Разгледайте ${typeLabel}${dealLabel}${regionLabel}. Актуални оферти, вътрешни линкове към детайлите и пълна информация за всеки имот.`,
  };
}

export function getPropertySearchSeoCopy(filters: PropertySearchFilters) {
  const baseCopy = getPropertiesSeoCopy(filters);

  if (!filters.search) {
    return {
      heading: "Търсене на имоти в Гърция",
      title: baseCopy.title === "Имоти в Гърция" ? "Търсене на имоти в Гърция" : baseCopy.title,
      description:
        "Използвайте търсачката и филтрите, за да откриете имоти в Гърция по тип, регион, цена и площ.",
    };
  }

  return {
    heading: `Резултати за "${filters.search}"`,
    title: `Търсене на имоти за "${filters.search}"`,
    description: `Резултати от търсене за "${filters.search}" в Гърция с филтри по тип имот, сделка, цена, площ и регион.`,
  };
}

export function getCanonicalPropertiesPath(filters: PropertiesFilters) {
  const params = new URLSearchParams();

  if (filters.dealType !== "all") {
    params.set("deal", filters.dealType);
  }

  if (filters.region !== "all") {
    params.set("region", filters.region);
  }

  const query = params.toString();
  return query ? `/properties?${query}` : "/properties";
}

export function getPropertySearchPath(
  filters: Partial<PropertySearchFilters>,
  basePath = "/search",
) {
  const params = new URLSearchParams();

  if (filters.search?.trim()) {
    params.set("search", filters.search.trim());
  }

  if (filters.dealType && filters.dealType !== "all") {
    params.set("deal", filters.dealType);
  }

  if (filters.propType && filters.propType !== "all") {
    params.set("type", filters.propType);
  }

  if (filters.region && filters.region !== "all") {
    params.set("region", filters.region);
  }

  if (typeof filters.priceRange === "number" && filters.priceRange !== 0) {
    params.set("priceRange", String(filters.priceRange));
  }

  if (typeof filters.areaRange === "number" && filters.areaRange !== 0) {
    params.set("areaRange", String(filters.areaRange));
  }

  if (filters.sortBy && filters.sortBy !== "newest") {
    params.set("sort", filters.sortBy);
  }

  if (filters.viewMode && filters.viewMode !== "grid") {
    params.set("view", filters.viewMode);
  }

  const query = params.toString();
  return query ? `${basePath}?${query}` : basePath;
}

export function shouldNoIndexProperties(filters: PropertiesFilters) {
  return (
    filters.propType !== "all" ||
    filters.priceRange !== 0 ||
    filters.areaRange !== 0 ||
    filters.sortBy !== "newest" ||
    filters.viewMode !== "grid"
  );
}

function normalizeSearchValue(value: string) {
  return value.toLocaleLowerCase("bg-BG").trim();
}

export function filterProperties(
  properties: Property[],
  filters: PropertiesFilters | PropertySearchFilters,
) {
  let result = [...properties];

  if (filters.dealType !== "all") {
    result = result.filter((property) => property.dealType === filters.dealType);
  }

  if (filters.propType !== "all") {
    result = result.filter((property) => property.propertyType === filters.propType);
  }

  if (filters.region !== "all") {
    result = result.filter(
      (property) =>
        property.location.region === filters.region || property.location.city === filters.region,
    );
  }

  const range = priceRanges[filters.priceRange];
  result = result.filter(
    (property) => property.price >= range.min && property.price < range.max,
  );

  const area = areaRanges[filters.areaRange];
  result = result.filter(
    (property) => property.area >= area.min && property.area < area.max,
  );

  if ("search" in filters && filters.search.trim()) {
    const search = normalizeSearchValue(filters.search);

    result = result.filter((property) => {
      const haystack = [
        property.id,
        property.title,
        property.description,
        property.propertyType,
        property.location.region,
        property.location.city,
        property.location.district || "",
        property.location.address || "",
        ...property.features,
      ]
        .join(" ")
        .toLocaleLowerCase("bg-BG");

      return haystack.includes(search);
    });
  }

  switch (filters.sortBy) {
    case "price-asc":
      result.sort((left, right) => left.price - right.price);
      break;
    case "price-desc":
      result.sort((left, right) => right.price - left.price);
      break;
    case "area-desc":
      result.sort((left, right) => right.area - left.area);
      break;
    default:
      result.sort(
        (left, right) =>
          new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime(),
      );
      break;
  }

  return result;
}

export function getFaqFilters(
  searchParams: Record<string, string | string[] | undefined>,
) {
  const search = pickFirst(searchParams.search)?.trim() ?? "";
  const category = pickFirst(searchParams.category) ?? "all";

  return {
    category,
    search,
  };
}
