"use client";

import { useCallback, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { FormikValues, useFormikContext } from "formik";
import FlagsSelect from "react-flags-select";
import { countryLabels } from "@/data/countryLabels";
import { DEFAULT_COUNTRY_SHORT_CODE } from "@/data/defaultCountry";
import { useTranslation } from "react-i18next";

interface CountryCodeSelectProps {
  name: string;
  disabled?: boolean;
  index?: number;
  className?: string;
  onChange?: (value: string) => void;
  value?: string;
}

const CountryCodeSelect = ({
  name,
  disabled,
  index,
  className,
  onChange,
  value,
}: CountryCodeSelectProps) => {
  const { t } = useTranslation();
  const containerRef = useRef<HTMLDivElement>(null);
  const [emptyList, setEmptyList] = useState<HTMLElement | null>(null);
  const { setFieldValue, values } = useFormikContext<FormikValues>();

  /*
   * The flag to show for a dial code. `DEFAULT_COUNTRY_SHORT_CODE` for
   * anything unrecognised, which is display-only — it never becomes the
   * form's value, so an unmatched code is shown as Kuwait but still submitted
   * as itself.
   */
  const findShortCodeByDialCode = useCallback((dialCode: string): string => {
    if (!dialCode) return DEFAULT_COUNTRY_SHORT_CODE;
    const entries = Object.entries(countryLabels);
    const matchingEntry = entries.find(([, label]) => label.secondary === dialCode);
    return matchingEntry ? matchingEntry[0] : DEFAULT_COUNTRY_SHORT_CODE;
  }, []);

  const getFieldValues = useCallback(() => {
    if (value !== undefined) {
      return {
        countryCode: value,
        countryShortCode: findShortCodeByDialCode(value),
      };
    }

    const formikValue = values[name];
    if (formikValue) {
      return {
        countryCode: formikValue,
        countryShortCode: findShortCodeByDialCode(formikValue),
      };
    }

    if (typeof index === "number") {
      return {
        countryCode: values.rows?.[index]?.countryCode,
        countryShortCode: values.rows?.[index]?.countryShortCode,
      };
    }

    return {
      countryCode: "",
      countryShortCode: "",
    };
  }, [value, values, name, index, findShortCodeByDialCode]);

  const setFields = useCallback((code: string, shortCode: string) => {
    if (typeof index === "number") {
      setFieldValue(`rows.${index}.countryCode`, code);
      setFieldValue(`rows.${index}.countryShortCode`, shortCode);
    } else {
      setFieldValue(name, code);
    }
  }, [index, name, setFieldValue]);

  /*
   * No seeding effect, and so no `react-hooks/set-state-in-effect` report.
   *
   * This component used to default the field to Kuwait from a mount effect,
   * because a child cannot default a value it does not own: `setFieldValue`
   * writes the `<Formik>` provider's state, an *ancestor's*, and React
   * permits a render-phase write only for the component doing the rendering.
   * The fix was not to find a legal place for the write but to remove the
   * need for it — the default is declared in each form's initial-values
   * builder, which is the owner (see `DEFAULT_DIAL_CODE` for the three
   * defects that effect caused, including a form that was `dirty` on mount
   * and a field left blank by `resetForm`).
   *
   * What remains below is a pure derivation of the flag to show from the
   * field's current value, and `handleSelect`, which writes in response to a
   * user event. The asynchronous case — a profile whose saved dial code
   * arrives from the API after mount — is handled by the owner too: both
   * account forms build their initial values from the query payload and pass
   * `enableReinitialize`, so the saved code flows in as initial state rather
   * than being pushed in from here. That is also why the `initialValue` prop
   * is gone: it only ever re-sent a value Formik already held.
   */
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;
    // The library has no empty-results render prop. Observe only this picker,
    // and render a non-selectable message inside its otherwise empty list.
    const observer = new MutationObserver(() => {
      const list = container.querySelector<HTMLElement>('[role="listbox"]');
      setEmptyList(list && !list.querySelector('[role="option"]') ? list : null);
    });
    observer.observe(container, { childList: true, subtree: true });
    return () => observer.disconnect();
  }, []);

  const handleSelect = (countryShortCode: string) => {
    const dialCode =
      countryLabels[countryShortCode as keyof typeof countryLabels]?.secondary;
    if (dialCode) {
      setFields(dialCode, countryShortCode);
      if (onChange) {
        onChange(dialCode);
      }
    }
  };

  const { countryShortCode } = getFieldValues();

  return (
    <div ref={containerRef} className={`country-code-picker relative w-full mb-4 ${className || ""}`}>
      <div className="relative">
        <FlagsSelect
          selected={countryShortCode}
          onSelect={handleSelect}
          searchable={true}
          searchPlaceholder={t("COMMON.SEARCHPLACEHOLDER")}
          disabled={disabled}
          className={`w-full border rounded-2xl h-[48px] bg-[#29246D]/[0.03] placeholder-black focus:outline-none ${
            disabled
              ? "bg-gray-100 text-gray-500"
              : "border-[#29246D1A]/10 text-secondary-500"
          }`}
          selectButtonClassName="w-full"
          showSelectedLabel={false}
          showSecondarySelectedLabel={true}
          showOptionLabel={true}
          showSecondaryOptionLabel={true}
          customLabels={countryLabels}
          countries={Object.keys(countryLabels)}
          placeholder={t("COMMON.SEARCHPLACEHOLDER")}
        />
        {emptyList && createPortal(
          <li role="status" className="px-2 py-3 text-center text-xs leading-relaxed text-secondary-102">
            {t("COMMON.COUNTRY_CODE_NO_RESULTS")}
          </li>,
          emptyList,
        )}
      </div>
    </div>
  );
};

export default CountryCodeSelect;
export { CountryCodeSelect };
