"use client";

import { useTranslation } from "react-i18next";
import { useQuery } from "@tanstack/react-query";
import moment from "moment";
import { getAchievementsChartData, getAchievementsTeamsData } from "@/features/achievements/services/achievementsApi";
import {
  type LeaderboardType,
  } from "./achievementsTypes";

/**
 * The public achievements screen's figures and leaderboards.
 *
 * The economic-impact number is derived from total hours times a configurable
 * rate, which the API supplies and the UI must not hardcode.
 */
export function useAchievements() {
  const { t } = useTranslation();
  const { data: apiResponseForChart, isLoading: chartLoading, error: chartError, refetch: refetchChart } = useQuery({
    queryKey: ["achievementsChartData"],
    queryFn: getAchievementsChartData,
  });

  const { data: apiResponseForTop, isLoading: topLoading, error: topError, refetch: refetchTop } = useQuery({
    queryKey: ["achievementsTeamsData"],
    queryFn: getAchievementsTeamsData,
  });

  const chartData = apiResponseForChart?.data;
  const topData = apiResponseForTop?.data;
  const totalVolunteerHours = chartData?.grand_total_hours;
  const vol_opp_completed = chartData?.volunteer_opportunities_completed;
  // The backend renamed both counters and kept the old keys as aliases:
  // learn & share → development, relief → outside Kuwait.
  const learnserve_opp_completed =
    chartData?.development_opportunities_completed ??
    chartData?.learn_serve_opportunities_completed;
  const relief_trips = chartData?.outside_kuwait_trips ?? chartData?.relief_trips;

  // Economic impact = volunteer hours × the backend's KWD rate. The rate is
  // admin-editable, so it is always read from the payload; the literal is only a
  // last resort for a response that predates the field.
  const economicImpactRate = chartData?.economic_impact_rate_kwd ?? 11;
  const economicImpact =
    chartData?.economic_impact_kwd ??
    (typeof totalVolunteerHours === "number"
      ? totalVolunteerHours * economicImpactRate
      : 0);

  /**
   * Beneficiaries, as two counters rather than one.
   *
   * They used to be a single «عدد المستفيدين» card showing
   * `beneficiaries_count` — the backend's *combined* total — with the split
   * offered only as a hover tooltip, which is invisible on a phone. The client
   * asked for the two halves on the face of the page, so the card that was the
   * total is now the volunteering half and the development half is its own
   * card beside it.
   *
   * Both numbers are the backend's own: `beneficiaries_breakdown` carries the
   * volunteering half, and `development_beneficiaries_count` is a top-level
   * counter the backend already computes for exactly this purpose. Nothing is
   * derived here — in particular the volunteering half is **not**
   * `beneficiaries_count` minus the other, which would silently absorb any
   * third category added later.
   */
  const beneficiariesBreakdown = chartData?.beneficiaries_breakdown;
  const volunteerBeneficiaries = beneficiariesBreakdown?.volunteer_opportunities;
  const developmentBeneficiaries = chartData?.development_beneficiaries_count;
  /* Kept for the callers that still report the combined figure. */
  const beneficiariesCount = chartData?.beneficiaries_count;

  /**
   * The backend flags which counters to show via `counter_visibility` on the
   * statistics payload — each flag is true only once its counter has a value
   * (BE-132 extended that to volunteer hours/opportunities).
   * Falls back to the previous zero-value heuristic for a payload that
   * predates the field.
   */
  const counterVisibility = chartData?.counter_visibility as
    | Record<string, boolean>
    | undefined;

  const showCounter = (key: string, hasValue: boolean) =>
    counterVisibility ? counterVisibility[key] === true : hasValue;

  const statCards: Array<{
    key: string;
    value: string;
    label: string;
    tooltip?: string;
    className: string;
    valueClassName: string;
  }> = [
    /* Gated like the rest: zero counters stay hidden (client, 2026-10-13). */
    ...(showCounter("volunteer_opportunities", Boolean(vol_opp_completed))
      ? [
          {
            key: "volunteer-opportunities",
            value: String(vol_opp_completed || 0),
            label: t("ACHIEVEMENTS.VOL_OPP_COMPLETED"),
            // Tile colours: client, 2026-10-19.
            className: "bg-[#5271FF]/20 text-[#5271FF]",
            valueClassName: "text-[#5271FF]",
          },
        ]
      : []),
    ...(showCounter("development", Boolean(learnserve_opp_completed))
      ? [
          {
            key: "development",
            value: String(learnserve_opp_completed || 0),
            label: t("ACHIEVEMENTS.LEARN_SERVE_COMPLETED"),
            className: "bg-[#70B4C2]/20 text-[#70B4C2]",
            valueClassName: "text-[#70B4C2]",
          },
        ]
      : []),
    ...(showCounter("beneficiaries", Boolean(volunteerBeneficiaries))
      ? [
          {
            key: "beneficiaries",
            // Pinned to en-US: a bare toLocaleString() follows the browser's
            // locale, which renders Arabic-Indic digits on an Arabic system.
            value: Number(volunteerBeneficiaries || 0).toLocaleString("en-US"),
            label: t("ACHIEVEMENTS.BENEFICIARIES"),
            className: "bg-[#29246D]/20 text-[#29246D]",
            valueClassName: "text-[#29246D]",
          },
        ]
      : []),
    /* Gated by the backend's own `development_beneficiaries` flag, which is
       separate from `development`: courses can exist with nobody having
       completed one yet. */
    ...(showCounter(
      "development_beneficiaries",
      Boolean(developmentBeneficiaries)
    )
      ? [
          {
            key: "development-beneficiaries",
            value: Number(developmentBeneficiaries || 0).toLocaleString("en-US"),
            label: t("ACHIEVEMENTS.DEVELOPMENT_BENEFICIARIES"),
            className: "bg-[#A076E3]/20 text-[#A076E3]",
            valueClassName: "text-[#A076E3]",
          },
        ]
      : []),
    ...(showCounter("outside_kuwait", Boolean(relief_trips))
      ? [
          {
            key: "outside-kuwait",
            value: String(relief_trips || 0),
            label: t("ACHIEVEMENTS.RELIEF_TRIP"),
            className: "bg-[#D9EF61]/20 text-[#5e6b23]",
            valueClassName: "text-[#5e6b23]",
          },
        ]
      : []),
    ...(showCounter("economic_impact", Boolean(economicImpact))
      ? [
          {
            key: "economic-impact",
            // KWD carries three decimals (hours × rate is fractional).
            value: `${economicImpact.toLocaleString("en-US", { minimumFractionDigits: 3, maximumFractionDigits: 3 })} ${t("COMMON.KWD")}`,
            label: t("ACHIEVEMENTS.ECONOMIC_IMPACT"),
            className: "bg-[#FC9555]/20 text-[#FC9555]",
            valueClassName: "text-[#FC9555]",
          },
        ]
      : []),
  ];

  // Keeps the row on one line whatever survived the zero-filter above.
  const statGridColumns =
    {
      1: "lg:grid-cols-1",
      2: "lg:grid-cols-2",
      3: "lg:grid-cols-3",
      4: "lg:grid-cols-4",
      5: "lg:grid-cols-5",
      /* Splitting beneficiaries in two made six reachable. Without this the
         map fell through to its four-column default and left a 4 + 2 row. */
      6: "lg:grid-cols-3",
    }[statCards.length] ?? "lg:grid-cols-4";

  /*
   * `cycleYear` / `cycleIndex` are gone from the signature.
   * `GET /statistics/top/` emits `cycle_type`, `cycle_scope`, `start_date` and
   * `end_date` — nothing else. `cycle_year` and `cycle_index` exist on the
   * backend's `Config` model and are read by `RankingCycle` to *compute* the
   * window, but they are never serialized, so the two arguments were always
   * `undefined`. The derivation below already covered that case, which is why
   * the titles have always been right; the parameters were dead weight that
   * read as though the payload carried them.
   */
  const buildLeaderboardTitle = (
    section: LeaderboardType,
    cycleType?: string,
    startDate?: string
  ) => {
    let year: number | undefined;
    let index: number | undefined;

    if (startDate) {
      const startMoment = moment(startDate);
      year = startMoment.year();

      switch (cycleType?.toLowerCase()) {
        case "monthly":
          index = startMoment.month() + 1;
          break;
        case "quarterly":
          index = Math.floor(startMoment.month() / 3) + 1;
          break;
        case "semi_annual":
          index = startMoment.month() < 6 ? 1 : 2;
          break;
        case "annual":
        default:
          index = 1;
          break;
      }
    }

    year = year || moment().year();
    index = index || 1;

    const getMonthName = (monthIndex: number) => {
      const monthKeys = [
        "COMMON.JANUARY", "COMMON.FEBRUARY", "COMMON.MARCH", "COMMON.APRIL",
        "COMMON.MAY", "COMMON.JUNE", "COMMON.JULY", "COMMON.AUGUST",
        "COMMON.SEPTEMBER", "COMMON.OCTOBER", "COMMON.NOVEMBER", "COMMON.DECEMBER"
      ];
      return t(monthKeys[monthIndex - 1] || monthKeys[0]);
    };

    const getQuarterName = (quarterIndex: number) => {
      return t(`COMMON.Q${quarterIndex}`);
    };

    const getHalfName = (halfIndex: number) => {
      return halfIndex === 1 ? t("COMMON.FIRST_HALF") : t("COMMON.SECOND_HALF");
    };

    let periodLabel = "";
    let translationKey = "";

    switch (cycleType?.toLowerCase()) {
      case "monthly":
        periodLabel = `${getMonthName(index)}\u00A0\u00A0${year}`;
        translationKey = "MONTHLY";
        break;
      case "quarterly":
        periodLabel = `${getQuarterName(index)}\u00A0\u00A0${year}`;
        translationKey = "QUARTERLY";
        break;
      case "semi_annual":
        periodLabel = `${getHalfName(index)}\u00A0\u00A0${year}`;
        translationKey = "SEMI_ANNUAL";
        break;
      case "annual":
      default:
        periodLabel = `${year}`;
        translationKey = "ANNUAL";
        break;
    }

    switch (section) {
      case "individuals":
        return t(`ACHIEVEMENTS.VOLUNTEER_HEROES_${translationKey}`, { period: periodLabel });
      case "teams":
        return t(`ACHIEVEMENTS.MOST_ACTIVE_TEAMS_${translationKey}`, { period: periodLabel });
      case "companies":
        return t(`ACHIEVEMENTS.ENTITIES_MADE_DIFFERENCE_${translationKey}`, { period: periodLabel });
      default:
        return t("COMMON.NO_DATA");
    }
  };

  /** A failed load is shown as an error, never as a page of hidden counters. */
  const loadError = chartError ?? topError ?? null;
  const retry = () => { void refetchChart(); void refetchTop(); };

  return {
    loadError,
    retry,
    apiResponseForChart,
    chartLoading,
    apiResponseForTop,
    topLoading,
    chartData,
    topData,
    totalVolunteerHours,
    vol_opp_completed,
    learnserve_opp_completed,
    relief_trips,
    economicImpactRate,
    economicImpact,
    beneficiariesCount,
    beneficiariesBreakdown,
    counterVisibility,
    showCounter,
    statCards,
    statGridColumns,
    buildLeaderboardTitle,
  };
}
