"use client";

import { useMemo } from "react";

import { useAuthStore } from "@/store/authStore";
import { useLanguageStore } from "@/store/languageStore";
import { useQuery } from "@tanstack/react-query";
import { getDropdownChoices } from "@/features/shared/services/dropdowns";
import * as Yup from "yup";
import { type AllEventsFiltersData } from "./AllEventFilterModal";

/** A `{label, value}` pair as the select inputs want it. */
export interface ChoiceOption {
  label: string;
  value: string;
}

import type { ChoiceItem } from "@/lib/choices";

/**
 * The all-events filter modal's defaults, choice lookups and submit.
 *
 * `defaultValues` lives here because it is both the form's initial state and
 * the yardstick `FilterStateReporter` compares against to decide whether the
 * filters are empty.
 */
export function useAllEventFilters() {
  /*
   * `useMemo` so the object has a stable identity.
   *
   * `FilterStateReporter` compares the live values against it inside an
   * effect. Rebuilt on every render, it could not be listed as a dependency —
   * the effect would then run on every render — which is exactly why that
   * effect carried an `exhaustive-deps` suppression. Memoized, the dependency
   * can be declared honestly and the suppression is gone.
   */
  const defaultValues: AllEventsFiltersData = useMemo(
    () => ({
      startDate: "",
      endDate: "",
      tags: [],
      location: "",
      gender: "",
      age: [null, null],
      type: "",
      participation_type: "",
      matchMyInterest: false,
      status: "",
    }),
    []
  );

  const selectedLanguage = useLanguageStore((s) => s.language);
  const user = useAuthStore((s) => s.user);

  const validationSchema = Yup.object().shape({
    startDate: Yup.string(),
    endDate: Yup.string().test(
      "endDate-after-startDate",
      selectedLanguage === "ar"
        ? "تاريخ الانتهاء يجب أن يكون بعد تاريخ البدء"
        : "End date must be after start date",
      function (value) {
        const { startDate } = this.parent;
        if (!startDate || !value) return true;
        return new Date(value) >= new Date(startDate);
      }
    ),
  });

  const { data: genderData, isLoading: genderLoading } = useQuery({
    queryKey: ["dropdown", "opportunity_gender"],
    queryFn: () => getDropdownChoices("opportunity_gender"),
  });

  const { data: eventTypeData, isLoading: eventTypeLoading } = useQuery({
    queryKey: ["dropdown", "event_type"],
    queryFn: () => getDropdownChoices("event_type"),
  });

  const { data: participationTypeData, isLoading: participationTypeLoading } = useQuery({
    queryKey: ["dropdown", "event_participation_type"],
    queryFn: () => getDropdownChoices("event_participation_type"),
  });

  const genderOptions =
    genderData?.data?.map((item: ChoiceItem) => ({
      label: selectedLanguage === "ar" ? item.value_ar : item.value_en,
      value: String(item.id),
    })) || [];

  const eventTypeOptions = (() => {
    const data = eventTypeData?.data || [];
    const isHub = (item: ChoiceItem) => item.value_en === "Hub";
    const hubItems = data.filter(isHub);
    const otherItems = data.filter((i: ChoiceItem) => !isHub(i));
    const ordered = [...hubItems, ...otherItems];
    return ordered.map((item: ChoiceItem) => ({
      label: selectedLanguage === "ar" ? item.value_ar : item.value_en,
      value: String(item.id),
    }));
  })();

  const participationTypeOrder = [
    "Free Event",
    "Free Event (Registration Required)",
    "Paid Event",
  ];

  const participationTypeOptions =
    participationTypeData?.data
      ?.map((item: ChoiceItem) => ({
        label: selectedLanguage === "ar" ? item.value_ar : item.value_en,
        value: String(item.id),
        value_en: item.value_en,
      }))
      .sort(
        /* Both sides are the option objects built just above, so the element
           type is inferred — the annotation only hid that `value_en` is what
           the sort reads. */
        (a, b) =>
          participationTypeOrder.indexOf(a.value_en) - participationTypeOrder.indexOf(b.value_en)
      ) || [];

  return {
    defaultValues,
    selectedLanguage,
    user,
    validationSchema,
    genderData,
    genderLoading,
    eventTypeData,
    eventTypeLoading,
    participationTypeData,
    participationTypeLoading,
    genderOptions,
    eventTypeOptions,
    participationTypeOrder,
    participationTypeOptions,
  };
}
