"use client";

import { Formik, Form, useFormikContext } from "formik";
import { useEffect } from "react";
import AllEventFilterFields from "./AllEventFilterFields";
import { useAllEventFilters } from "./useAllEventFilters";

export interface AllEventFilterModalProps {
  onApply: (filters: AllEventsFiltersData) => void;
  initialValues?: AllEventsFiltersData;
  onDirtyChange?: (dirty: boolean) => void;
  onEmptyChange?: (isEmpty: boolean) => void;
  isInnerModal?: boolean;
}

export interface AllEventsFiltersData {
  startDate: string;
  endDate: string;
  tags: string[];
  location: string;
  gender: string;
  age: [number | null, number | null];
  type: string;
  participation_type: string;
  matchMyInterest: boolean;
  status: string;
}

/**
 * Reports dirty/empty state from inside the Formik tree via context, rather
 * than calling `useEffect` directly in the render prop (not a valid hook
 * position — see `VolunteerFilterModal.tsx`'s `DirtyReporter` for the same
 * pattern).
 */
function FilterStateReporter({
  defaultValues,
  onDirtyChange,
  onEmptyChange,
}: {
  defaultValues: AllEventsFiltersData;
  onDirtyChange?: (dirty: boolean) => void;
  onEmptyChange?: (isEmpty: boolean) => void;
}) {
  const { values, dirty } = useFormikContext<AllEventsFiltersData>();

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

  /* `defaultValues` is listed rather than suppressed: `useAllEventFilters`
     memoizes it, so it is referentially stable and cannot make this re-run.
     Before that it was rebuilt on every render, which is why the dependency
     could not be declared. */
  useEffect(() => {
    onEmptyChange?.(JSON.stringify(values) === JSON.stringify(defaultValues));
  }, [values, onEmptyChange, defaultValues]);

  return null;
}

function AllEventFilterModal({
  onApply,
  initialValues,
  onDirtyChange,
  onEmptyChange,
  isInnerModal,
}: AllEventFilterModalProps) {
  const {
    defaultValues,
    user,
    validationSchema,
    genderLoading,
    eventTypeLoading,
    participationTypeLoading,
    genderOptions,
    eventTypeOptions,
    participationTypeOptions,
  } = useAllEventFilters();

  /* No `GoogleMapsProvider`: 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 event *form* still mounts the provider, because creating an event
     still picks a location. */
  return (
    <Formik
        initialValues={initialValues || defaultValues}
        validationSchema={validationSchema}
        onSubmit={(values) => {
          onApply(values);
        }}
      >
        {() => {
          return (
            <Form className="event-modal">
              <FilterStateReporter
                defaultValues={defaultValues}
                onDirtyChange={onDirtyChange}
                onEmptyChange={onEmptyChange}
              />
              <AllEventFilterFields
                isInnerModal={isInnerModal}
                genderOptions={genderOptions}
                eventTypeOptions={eventTypeOptions}
                participationTypeOptions={participationTypeOptions}
                genderLoading={genderLoading}
                eventTypeLoading={eventTypeLoading}
                participationTypeLoading={participationTypeLoading}
                isLoggedIn={Boolean(user)}
              />
            </Form>
          );
        }}
      </Formik>
  );
}

export default AllEventFilterModal;
