import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
import { toast } from "sonner";
import { t } from "i18next";
import moment from "moment";
import { parseLocalizedNumber, toWesternDigits } from "@/lib/digits";
import { authoringCalendarDay } from "@/features/shared/opportunityFormRules";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

/**
 * Parse a numeric field that may arrive as an Arabic-Indic digit string.
 *
 * Responses are already normalized at the axios boundary (`lib/api/client.ts`),
 * so in practice this now receives ASCII — but it stays tolerant for values
 * that reach the UI by another route (sessionStorage payloads, SSR props,
 * anything hand-built), and it is still the right call before doing arithmetic
 * on an API count.
 */
export const toNumber = parseLocalizedNumber;

/**
 * A price as a card tag shows it: `33` → `"33 KWD"` / `"33 د.ك"`, `12.5` →
 * `"12.5 …"`, `7.25` → `"7.25 …"` — up to the dinar's three decimals, with the
 * trailing zeros dropped so a round price reads as a round number. `null`
 * when there is no positive amount, so the caller can fall back to «مدفوعة».
 */
export const formatPriceTag = (
  value: unknown,
  t: (key: string) => string
): string | null => {
  if (value === null || value === undefined || value === "") return null;
  const amount = parseLocalizedNumber(value);
  if (!(amount > 0)) return null;
  return `${Number(amount.toFixed(3))} ${t("COMMON.KWD_SHORT")}`;
};

/**
 * Render a numeric field as digits.
 *
 * Digits deliberately do **not** follow the UI language: this product renders
 * `12345` in Arabic exactly as in English, so unlike the rest of the i18n layer
 * there is nothing to switch on. Kept as a named helper (rather than inlining
 * `toWesternDigits`) because it also pins the empty/missing case to `"0"`,
 * which the stat cards rely on.
 */
export const toDisplayDigits = (value: unknown): string => {
  if (value === null || value === undefined || value === "") return "0";
  return toWesternDigits(value);
};

/**
 * Whether a profile counter is 1 or more. The client's rule: a counter that is
 * still at zero is not shown at all. Takes whatever the API sent — a number, a
 * numeric string, Arabic-Indic digits — and treats anything unparseable as 0.
 */
export const hasPositiveCount = (value: unknown): boolean =>
  Number(toDisplayDigits(value).replace(/,/g, "")) > 0;

export const maskEmail = (email: string) => {
  if (!email) return "";
  const [name, domain] = email.split("@");
  if (name.length > 3) {
    return `${name.substring(0, 3)}********@${domain}`;
  }
  return `${name}********@${domain}`;
};


/**
 * The silhouette to draw for an account with no picture of its own.
 *
 * Matching is case- and space-insensitive. `/choices/gender/` answers `Male`
 * and `Female` today, but this value reaches the UI from six different
 * payloads and an admin can rename a choice row — and the failure mode of an
 * exact match is silent: every volunteer is simply drawn as the neutral
 * default, which looks like a styling choice rather than a bug. It cost two
 * rounds to find once already.
 *
 * `defaultImg` is the organization mark at every call site, which is also the
 * right answer for an organization: gender hangs off the volunteer profile, so
 * an organization has none.
 */
export const getDefaultProfileImage = (
  /* Nullable: `*_display` keys are omitted and their values nulled by the API. */
  gender: string | null | undefined,
  maleImg: string,
  femaleImg: string,
  defaultImg: string
): string => {
  const normalized = gender?.trim().toLowerCase();
  if (normalized === "male") return maleImg;
  if (normalized === "female") return femaleImg;
  return defaultImg;
};

/**
 * Reverse/forward geocoding for the location map pickers (create/edit event,
 * volunteer opportunity, learn & serve opportunity). Uses OpenStreetMap's
 * Nominatim rather than Google's Geocoding API — that API rejects
 * referrer-restricted keys outright ("API keys with referer restrictions
 * cannot be used with this API"), and the referrer restriction is the
 * correct one for a key that's otherwise embedded in client-side JS. Nominatim
 * also matches the OSM tiles `LocationMapPicker` already renders, and needs
 * no key. Its usage policy requires a valid Referer identifying the caller —
 * satisfied automatically by the browser's own Referrer-Policy header, no
 * code needed. `nominatim.openstreetmap.org` is on the CSP `connect-src`
 * allowlist in `next.config.ts`.
 */
const NOMINATIM_BASE_URL = "https://nominatim.openstreetmap.org";
// Most opportunities/events are in Kuwait (see LocationMapPicker's default map
// center) — searching it first avoids forward-geocoding a generic place name
// to the wrong country; `fetchCoordinates` falls back to a worldwide search.
const NOMINATIM_COUNTRY_CODE = "kw";

interface NominatimAddress {
  road?: string;
  neighbourhood?: string;
  suburb?: string;
  city_district?: string;
  city?: string;
  town?: string;
  village?: string;
  state?: string;
  country?: string;
}

export const fetchAddress = async (
  latitude: number,
  longitude: number,
  language = "en",
  isSmallAddress = false
): Promise<string> => {
  try {
    const response = await fetch(
      `${NOMINATIM_BASE_URL}/reverse?format=jsonv2&lat=${latitude}&lon=${longitude}&accept-language=${language}`
    );
    const data = await response.json();

    if (data && !data.error) {
      if (isSmallAddress) {
        const address: NominatimAddress = data.address || {};
        const parts = [
          address.road || address.neighbourhood || address.suburb,
          address.city_district ||
            address.city ||
            address.town ||
            address.village ||
            address.state,
        ].filter(Boolean);
        return parts.length > 0
          ? parts.join(", ")
          : t("COMMON.ADDRESS_NOT_FOUND");
      }
      return data.display_name || t("COMMON.ADDRESS_NOT_FOUND");
    }
    return t("COMMON.ADDRESS_NOT_FOUND");
  } catch (error) {
    console.error("Error fetching address:", error);
    return t("COMMON.ADDRESS_NOT_FOUND");
  }
};

export const fetchCoordinates = async (
  address: string,
  language = "en"
): Promise<{ lat: number; lng: number } | null> => {
  /* Kuwait first, then anywhere: opportunities may take place outside Kuwait
     (p.12/p.14 «خارج الكويت»), and a Kuwait-only search could never place a
     foreign address on the map. */
  const search = async (countryCodes: string) => {
    const response = await fetch(
      `${NOMINATIM_BASE_URL}/search?format=jsonv2&q=${encodeURIComponent(
        address
      )}&accept-language=${language}${countryCodes ? `&countrycodes=${countryCodes}` : ""}&limit=1`
    );
    const data = await response.json();
    return Array.isArray(data) && data.length > 0
      ? { lat: parseFloat(data[0].lat), lng: parseFloat(data[0].lon) }
      : null;
  };
  try {
    return (await search(NOMINATIM_COUNTRY_CODE)) ?? (await search(""));
  } catch (error) {
    console.error("Error fetching coordinates:", error);
    return null;
  }
};

/**
 * Append a cache-busting query to an uploaded image URL. The API overwrites a
 * profile picture in place, so the URL is unchanged after a re-upload and the
 * browser would keep serving the previous file from cache.
 *
 * Call this from an event handler or effect — never during render, where the
 * timestamp would differ between the server and client markup.
 */
export const withCacheBust = (url?: string | null): string => {
  if (!url) return "";
  return `${url}${url.includes("?") ? "&" : "?"}t=${Date.now()}`;
};

/**
 * Open an opportunity's / event's location: the map link the organiser saved in
 * `location_url` when there is one, otherwise a Google Maps search built from
 * the stored coordinates.
 */
/**
 * The URL an address points at, or `null` when the record carries neither a
 * link nor coordinates.
 *
 * Split out of `openLocation` so the three address rows can render a real
 * `<a href>` instead of a click handler. That is not a cosmetic change: an `<a>`
 * is reachable by keyboard, announced as a link, and supports middle-click and
 * "open in new tab", none of which a `window.open` on a `<p>` does. It also lets
 * a row with no destination render as plain text rather than as something that
 * looks clickable and silently does nothing — which is what the old handler did
 * when both branches fell through.
 */
export const locationHref = (
  locationUrl?: string | null,
  latitude?: number | string | null,
  longitude?: number | string | null
): string | null => {
  const url = locationUrl?.trim();
  if (url) {
    /* The column holds whatever the organizer pasted, which is often
       `maps.google.com/...` with no scheme — a protocol-relative href would
       resolve against the Fursa origin. */
    return /^https?:\/\//i.test(url) ? url : `https://${url}`;
  }

  const hasCoordinates =
    latitude !== null &&
    latitude !== undefined &&
    latitude !== "" &&
    longitude !== null &&
    longitude !== undefined &&
    longitude !== "";

  return hasCoordinates
    ? `https://www.google.com/maps/search/?api=1&query=${latitude},${longitude}`
    : null;
};

/** Kept for the callers that still open the map imperatively. */
export const openLocation = (
  locationUrl?: string | null,
  latitude?: number | string | null,
  longitude?: number | string | null
) => {
  const href = locationHref(locationUrl, latitude, longitude);
  if (href) window.open(href, "_blank", "noopener");
};

export const handleShare = async (url: string, t: (key: string) => string) => {
  const shareData = {
    url: url,
  };

  if (typeof navigator !== "undefined" && navigator.share) {
    try {
      await navigator.share(shareData);
    } catch {
      toast.error(t("COMMON.SHARE_FAILED"));
    }
  } else if (typeof navigator !== "undefined" && navigator.clipboard) {
    navigator.clipboard.writeText(shareData.url).then(
      () => toast.success(t("COMMON.URL_COPIED")),
      () => toast.error(t("COMMON.SHARE_FAILED"))
    );
  }
};

export const calculateHoursDifference = (
  startTime: string,
  endTime: string
): string => {
  if (!startTime || !endTime) return "";
  const [startHour, startMinute] = startTime.split(":").map(Number);
  const [endHour, endMinute] = endTime.split(":").map(Number);

  const startTotalMinutes = startHour * 60 + startMinute;
  const endTotalMinutes = endHour * 60 + endMinute;

  let diffMinutes = endTotalMinutes - startTotalMinutes;
  if (diffMinutes < 0) diffMinutes += 24 * 60; // Handle cases where endTime is on the next day

  const hours = (diffMinutes / 60).toFixed(2); // Return with 2 decimal places
  return hours;
};

export const formatDateToYYYYMMDD = (dateInput: string | Date): string => {
  if (!dateInput) return "";
  return authoringCalendarDay(dateInput);
};

export function formatSingleDate(
  date: string,
  locale: string,
  t: (key: string) => string
): string {
  if (!date) {
    return t("COMMON.INVALID_DATE"); // Fallback translation key
  }
  const [year, month, day] = date?.split("-")?.map(Number);

  const monthKeys = {
    1: "COMMON.JANUARY",
    2: "COMMON.FEBRUARY",
    3: "COMMON.MARCH",
    4: "COMMON.APRIL",
    5: "COMMON.MAY",
    6: "COMMON.JUNE",
    7: "COMMON.JULY",
    8: "COMMON.AUGUST",
    9: "COMMON.SEPTEMBER",
    10: "COMMON.OCTOBER",
    11: "COMMON.NOVEMBER",
    12: "COMMON.DECEMBER",
  };

  const monthKey = monthKeys[month as keyof typeof monthKeys];
  const formattedDay = String(day)?.padStart(2, "0");

  if (locale === "ar") {
    return `${formattedDay} ${t(monthKey)} ${year}`;
  }
  return `${t(monthKey)} ${formattedDay}, ${year}`;
}

export function formatDateRange(
  start_date: string,
  end_date: string,
  locale: string,
  t?: (key: string) => string
) {
  const start = moment(start_date, "YYYY-MM-DD");
  const end = moment(end_date, "YYYY-MM-DD");

  const startDay = start.format("DD");
  const endDay = end.format("DD");
  const startMonth = start.month() + 1; // moment months are 0-indexed
  const endMonth = end.month() + 1;

  // Month translation mapping
  const monthKeys = {
    1: "COMMON.JANUARY",
    2: "COMMON.FEBRUARY",
    3: "COMMON.MARCH",
    4: "COMMON.APRIL",
    5: "COMMON.MAY",
    6: "COMMON.JUNE",
    7: "COMMON.JULY",
    8: "COMMON.AUGUST",
    9: "COMMON.SEPTEMBER",
    10: "COMMON.OCTOBER",
    11: "COMMON.NOVEMBER",
    12: "COMMON.DECEMBER",
  };

  if (start.isValid() && end.isValid() && start.isSame(end, "day")) {
    const monthKey = monthKeys[startMonth as keyof typeof monthKeys];
    return `${startDay} ${t ? t(monthKey) : start.locale(locale).format("MMMM")}`;
  }

  // If t is not available (during initial render), fall back to moment localization
  if (!t) {
    start.locale(locale);
    end.locale(locale);
    if (startMonth === endMonth) {
      if (locale === "ar") {
        return `${endDay}-${startDay} ${start.format("MMMM")}`;
      }
      return `${startDay}-${endDay} ${start.format("MMMM")}`;
    } else {
      if (locale === "ar") {
        return `${end.format("DD MMMM")} - ${start.format("DD MMMM")}`;
      }
      return `${start.format("DD MMMM")} - ${end.format("DD MMMM")}`;
    }
  }

  // With translation function available
  const startMonthKey = monthKeys[startMonth as keyof typeof monthKeys];
  const endMonthKey = monthKeys[endMonth as keyof typeof monthKeys];

  if (startMonth === endMonth) {
    if (locale === "ar") {
      return `${endDay}-${startDay} ${t(startMonthKey)}`;
    }
    return `${startDay}-${endDay} ${t(startMonthKey)}`;
  } else {
    if (locale === "ar") {
      return `${startDay} ${t(startMonthKey)} - ${endDay} ${t(endMonthKey)}`;
    }
    return `${startDay} ${t(startMonthKey)} - ${endDay} ${t(endMonthKey)}`;
  }
}

