"use client";

import { Formik, Form, useFormikContext } from "formik";
import { useLanguageStore } from "@/store/languageStore";
import {
  buildOpportunityTypeOptions,
  developmentTypeCatalog,
  type ChoiceItem,
} from "./opportunityTypeOptions";
import OpportunityFilterFields from "./OpportunityFilterFields";
import {
  EMPTY_OPPORTUNITY_FILTERS,
  type AllOpportunitiesFiltersData,
} from "./opportunityFilters";
import { useQuery } from "@tanstack/react-query";
import { getDropdownChoices } from "@/features/shared/services/dropdowns";
import { useEffect, useMemo } from "react";

interface AllOpportunitiesFilterModalProps {
  onApply: (filters: AllOpportunitiesFiltersData) => void;
  initialValues?: AllOpportunitiesFiltersData;
  onDirtyChange?: (dirty: boolean) => void;
  onEmptyChange?: (isEmpty: boolean) => void;
  showLearnServeFields?: boolean;
  showVolunteerFields?: boolean;
}

function FilterStateReporter({
  defaultValues,
  onDirtyChange,
  onEmptyChange,
}: {
  defaultValues: AllOpportunitiesFiltersData;
  onDirtyChange?: (dirty: boolean) => void;
  onEmptyChange?: (isEmpty: boolean) => void;
}) {
  const { values, dirty } = useFormikContext<AllOpportunitiesFiltersData>();

  useEffect(() => {
    onDirtyChange?.(dirty);
  }, [dirty, onDirtyChange]);

  useEffect(() => {
    onEmptyChange?.(JSON.stringify(values) === JSON.stringify(defaultValues));
  }, [values, onEmptyChange, defaultValues]);

  return null;
}

const OpportuniteFilterModal = ({
  onApply,
  initialValues,
  onDirtyChange,
  onEmptyChange,
  showLearnServeFields,
  showVolunteerFields,
}: AllOpportunitiesFilterModalProps) => {
  /* `useMemo` so the identity is stable: `FilterStateReporter` compares the
     live values against it inside an effect, and a factory call on every
     render meant the dependency could not be listed — the effect would have
     run every render. That is what its `exhaustive-deps` suppression was for;
     memoized, the dependency is declared instead. */
  const defaultValues: AllOpportunitiesFiltersData = useMemo(
    () => EMPTY_OPPORTUNITY_FILTERS(),
    []
  );

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

  /* The development list filters on `learning_type_id`, which takes a
     `learning_type` id — the `filter-type` ids are a different catalog the
     development endpoint ignores (`LearnServeOpportunityController::index`). */
  const typeCatalog = developmentTypeCatalog({ showVolunteerFields, showLearnServeFields });
  const { data: typeData, isLoading: typeLoading } = useQuery({
    queryKey: ["dropdown", typeCatalog],
    queryFn: () => getDropdownChoices(typeCatalog),
  });

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

  const typeOptions = buildOpportunityTypeOptions({
    choices: typeData?.data,
    selectedLanguage,
    showVolunteerFields,
    showLearnServeFields,
  });

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

  /* No `GoogleMapsProvider` any more: the Places autocomplete behind the
     location field was the only thing in this form that needed the Maps SDK,
     and the field is gone. The provider stays mounted on the opportunity
     *forms*, which still pick a location. */
  return (
    <>
      <Formik
        initialValues={initialValues || defaultValues}
        onSubmit={(values) => {
          onApply(values);
        }}
      >
        {({ setFieldValue }) => {
          return (
            <Form className="opp-modal">
              <FilterStateReporter
                defaultValues={defaultValues}
                onDirtyChange={onDirtyChange}
                onEmptyChange={onEmptyChange}
              />
              <div className="pb-[10px] xss:pb-[20px]">
                <OpportunityFilterFields
                  setFieldValue={setFieldValue}
                  typeOptions={typeOptions}
                  typeLoading={typeLoading}
                  genderOptions={genderOptions}
                  genderLoading={genderLoading}
                  showVolunteerFields={showVolunteerFields}
                  showLearnServeFields={showLearnServeFields}
                />
                {/* `OpportunityFilterFlags` is deliberately *not* mounted
                    here. `OpportunityFilterFields` above renders it as part of
                    its own grid — the toggles are cells in that grid, which is
                    what lets them take a line of their own. Mounting it here
                    too would render every toggle twice, each half bound to the
                    same Formik field. */}
              </div>
            </Form>
          );
        }}
      </Formik>
    </>
  );
};

export default OpportuniteFilterModal;
export type { AllOpportunitiesFilterModalProps };
/*
 * Re-exported so the four screens that import the type from this component keep
 * working. The declaration itself moved to `opportunityFilters.ts`: a type is
 * not a component's to own, and `VolunteerCard` had grown a second copy.
 */
export type { AllOpportunitiesFiltersData } from "./opportunityFilters";
