"use client";

import type { CSSObjectWithLabel } from "react-select";
import type { Role } from "./volunteerListHelpers";
import { useEffect } from "react";
import { Form, Formik, useFormikContext } from "formik";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import Select from "react-select";
import { useSelectMenuPortal, selectMenuPortalStyle } from "@/components/ui/SelectMenuPortal";

import { getRolesOfOpportunity } from "@/features/opportunities/services/roles";
import { usePageCursor, usePagedItems } from "@/features/shared/pagedList";
import { useLanguageStore } from "@/store/languageStore";

interface VolunteerFilterModalProps {
  opportunityId: string;
  onFilterChange: (filters: { roles?: string[] }) => void;
  currentFilters: { roles?: string[] };
  onDirtyChange?: (dirty: boolean) => void;
  onEmptyChange?: (isEmpty: boolean) => void;
}

interface SelectOption {
  label: string;
  value: string;
}

interface FormValues {
  roles: number[];
}

/**
 * Formik's render prop is not a valid hook position — it runs during the
 * parent's render and is not itself a component — so the dirty/empty flags are
 * reported from a child component that can legally hold the effect.
 */
function DirtyReporter({
  onDirtyChange,
  onEmptyChange,
}: {
  onDirtyChange?: (dirty: boolean) => void;
  onEmptyChange?: (isEmpty: boolean) => void;
}) {
  const { dirty, values } = useFormikContext<FormValues>();

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

  useEffect(() => {
    onEmptyChange?.(values.roles.length === 0);
  }, [values, onEmptyChange]);

  return null;
}

export default function VolunteerFilterModal({
  opportunityId,
  onFilterChange,
  currentFilters,
  onDirtyChange,
  onEmptyChange,
}: VolunteerFilterModalProps) {
  const { t } = useTranslation();
  const menuPortalProps = useSelectMenuPortal();
  const selectedLanguage = useLanguageStore((s) => s.language);

  // Options accumulate across pages as the menu is scrolled — see
  // `features/shared/pagedList`, which replaces the page number, the
  // `rolesList` mirror and the effect that appended to it.
  const { page: rolePage, nextPage } = usePageCursor(opportunityId);

  const {
    data: rolesData,
    isLoading: rolesLoading,
    isFetching,
  } = useQuery({
    queryKey: ["opportunity-roles", opportunityId, rolePage],
    queryFn: () =>
      getRolesOfOpportunity({
        opportunity_id: opportunityId,
        page: rolePage,
        limit: 10,
      }),
    enabled: Boolean(opportunityId),
  });

  const { items: rolesList, hasMore } = usePagedItems<Role>({
    resetSignature: opportunityId,
    response: rolesData,
    isFetching,
    limit: 10,
    dedupeById: true,
  });

  /* `hasMore` is the last-page guard this handler never had: it incremented
     the page on every scroll, so a menu scrolled at the bottom of a one-page
     list issued a request per scroll event, forever. The other two role
     pickers already stopped at `total_pages`. */
  const handleRoleMenuScroll = () => {
    if (!rolesLoading && !isFetching && hasMore) nextPage();
  };

  /* Explicit branch, not `role[`role_name_${lang}`]`: both columns are
     nullable, and `String(null)` is the four-character string `"null"` —
     which is what the dropdown would have shown for a role saved without a
     name in the active language. */
  const isArabic = selectedLanguage === "ar";
  const roleOptions: SelectOption[] = rolesList.map((role) => ({
    label: (isArabic ? role.role_name_ar : role.role_name_en) ?? "",
    value: String(role.id),
  }));

  const customStyles = {
    menuPortal: selectMenuPortalStyle,
    /* react-select hands each style function the base style object; its own
       type for that is `CSSObjectWithLabel`. */
    multiValueRemove: (provided: CSSObjectWithLabel) => ({
      ...provided,
      ":hover": {
        backgroundColor: "transparent",
      },
    }),
  };

  return (
    <Formik<FormValues>
      initialValues={{
        roles: currentFilters.roles ? currentFilters.roles.map(Number) : [],
      }}
      onSubmit={(values) => {
        onFilterChange({
          roles: values.roles.length > 0 ? values.roles.map(String) : undefined,
        });
      }}
    >
      {({ setFieldValue, values }) => (
        <div className="md:w-[100%] rounded-lg bg-white pb-[20px] xss:pb-[30px] filtermodal">
          <Form>
            <DirtyReporter
              onDirtyChange={onDirtyChange}
              onEmptyChange={onEmptyChange}
            />
            {/* Single column now that teams are gone — one select in a
                two-column grid left a conspicuous empty half. */}
            <div className="grid grid-cols-1 gap-x-6 gap-y-4 relative selectfiled">
              <div>
                <Select<SelectOption, true>
                  noOptionsMessage={() => t("COMMON.NO_SELECT_OPTIONS")}
                  loadingMessage={() => t("COMMON.LOADING")}
                  {...menuPortalProps}
                  className="w-full"
                  options={roleOptions}
                  value={roleOptions.filter((option) =>
                    values.roles.includes(Number(option.value)),
                  )}
                  onChange={(selectedOptions) =>
                    setFieldValue(
                      "roles",
                      selectedOptions
                        ? selectedOptions.map((option) => Number(option.value))
                        : [],
                    )
                  }
                  onMenuScrollToBottom={handleRoleMenuScroll}
                  isLoading={rolesLoading}
                  isDisabled={rolesLoading}
                  placeholder={t("COMMON.SELECT.ROLE")}
                  isMulti
                  styles={customStyles}
                />
              </div>
            </div>
          </Form>
        </div>
      )}
    </Formik>
  );
}
