"use client";

import Image from "next/image";
import React, { useMemo, useState, useEffect, useRef } from "react";
import {
  usePhoneInput,
  defaultCountries,
  parseCountry,
  type ParsedCountry,
  type CountryIso2,
  FlagImage,
} from "react-international-phone";
import "react-international-phone/style.css";

const FLAG_URL = "https://purecatamphetamine.github.io/country-flag-icons/3x2";

export interface PhoneInputProps {
  /**
   * Current value: digits only (country code + national number) for backend.
   * E.g. "12133734253" for +1 213 373 4253
   */
  value: string;
  /**
   * Called with digits only (country code + national number) for backend.
   * User selects country from dropdown and types national number - cannot type country code.
   */
  onChange: (value: string) => void;
  /** Optional label above the input */
  label?: string;
  /**
   * Marks the field required: an asterisk on the label and `aria-required` on
   * the input. Both, always — the glyph is the sighted half of the same fact
   * and `aria-required` is the other, and a field that announces one without
   * the other is the bug this replaces.
   */
  required?: boolean;
  /** Error message to show below the input */
  error?: string;
  /** Input id for label association */
  id?: string;
  /** Placeholder when no value */
  placeholder?: string;
  /** Default country (e.g. 'us', 'in') - use lowercase iso2 */
  defaultCountry?: string;
  /** Disable input and dropdown */
  disabled?: boolean;
  /** Countries to show at top of dropdown list */
  preferredCountries?: string[];
  /**
   * When set, called with dial code (+CC) and national digits whenever the value changes
   * (including country-only changes). Compose the `value` prop from dial + national in the parent when using this.
   */
  onValuePartsChange?: (parts: {
    dialCode: string;
    nationalNumber: string;
  }) => void;
  /** Additional class for the wrapper div */
  className?: string;
  /** Additional class for the input element */
  inputClass?: string;
  /** Props passed to the underlying input element */
  inputProps?: React.InputHTMLAttributes<HTMLInputElement>;
}

/**
 * Convert stored digits to E.164 for the library.
 * "12133734253" -> "+12133734253"
 */
function toE164(digits: string): string {
  const trimmed = digits?.replace(/\D/g, "") || "";
  if (!trimmed) return "";
  return `+${trimmed}`;
}

/**
 * Convert E.164 from library to digits for backend.
 * "+12133734253" -> "12133734253"
 */
function toDigits(e164: string): string {
  if (!e164) return "";
  return e164.replace(/^\+/, "").replace(/\D/g, "");
}

/** Build parsed countries list with preferred first */
function buildCountryOptions(
  preferred: string[] = ["us", "in", "gb"]
): ParsedCountry[] {
  const parsed = defaultCountries.map((c) => parseCountry(c));
  const prefSet = new Set(preferred.map((p) => p.toLowerCase()));
  const preferredList = parsed.filter((c) => prefSet.has(c.iso2));
  const rest = parsed.filter((c) => !prefSet.has(c.iso2));
  return [...preferredList, ...rest];
}

/**
 * Phone input with country selector (flags, searchable dropdown).
 * - User selects country from dropdown with flags + search
 * - User types only national number (cannot type country code)
 * - Backend receives: country code + phone (digits only)
 */
export function PhoneInput({
  value,
  onChange,
  label,
  required,
  error,
  id = "phone",
  placeholder = "Phone number",
  defaultCountry = "us",
  disabled = false,
  preferredCountries = ["us", "uk", "gb"],
  onValuePartsChange,
  className = "",
  inputClass = "",
  inputProps = {},
}: PhoneInputProps) {
  const hasError = !!error;
  const e164Value = toE164(value);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const rootRef = useRef<HTMLDivElement>(null);
  const [openUpwards, setOpenUpwards] = useState(false);
  /**
   * What this component last emitted, so a value coming back through the
   * parent's state can be told apart from one that arrived from elsewhere.
   *
   * Two forms, because callers consume two different props and echo back
   * whichever they were given: `onValuePartsChange` callers rebuild the full
   * dial-code-plus-national digits, while `onChange` callers store exactly what
   * it passed — and that is deliberately `""` when only a dial code is present,
   * so optional validation does not fail on a country with no number yet.
   *
   * State rather than a ref: it is read during render to decide a config value
   * the hook consumes on that same render, and reading a mutable ref there is
   * not safe under concurrent rendering.
   */
  const [lastEmitted, setLastEmitted] = useState({ full: "", reported: "" });

  /** True when `value` did not come from this component's own last emission. */
  const incomingDigits = toDigits(value);
  const isExternalValue =
    incomingDigits !== lastEmitted.full && incomingDigits !== lastEmitted.reported;

  const countryOptions = useMemo(
    () => buildCountryOptions(preferredCountries),
    [preferredCountries]
  );

  const filteredCountries = useMemo(() => {
    if (!searchQuery.trim()) return countryOptions;
    const q = searchQuery.toLowerCase();
    return countryOptions.filter(
      (c) =>
        c.name.toLowerCase().includes(q) ||
        c.dialCode.includes(q) ||
        c.iso2.toLowerCase().includes(q)
    );
  }, [countryOptions, searchQuery]);

  const {
    phone,
    inputValue,
    country,
    setCountry,
    handlePhoneValueChange,
    inputRef,
  } = usePhoneInput({
    defaultCountry: defaultCountry.toLowerCase() as CountryIso2,
    value: e164Value,
    preferredCountries: preferredCountries.map((p) =>
      p.toLowerCase()
    ) as CountryIso2[],
    // Allow up to 15 digits across countries. With formatting disabled, the mask length becomes the input cap.
    disableFormatting: true,
    defaultMask: "...............", // 15 digits
    forceDialCode: true,
    disableDialCodeAndPrefix: true,
    /**
     * Guess the country from a number that arrived from outside; never from one
     * being typed.
     *
     * Guessing re-derives the country on every value change, and for a dial code
     * shared by several countries it cannot honour an explicit choice. +1 is the
     * clear case: the library's US entry has no `areaCodes` and priority 0,
     * while Canada has 42 area codes and priority 1, so its "keep the current
     * country" branch is gated on the digits so far matching a Canadian area
     * code. Pick Canada, type a number whose area code is not on that list, and
     * the field silently flips to the United States.
     *
     * While typing it buys nothing anyway: `disableDialCodeAndPrefix` means only
     * the national number is typed, so there is no dial code in that input to
     * infer a country from. For a value loaded from the server it is exactly
     * right, and better than anything done here could be — a whole +1 416…
     * resolves to Canada on its area code, where a half-typed one cannot.
     *
     * Deliberately not solved with `setCountry`: that resets the input to an
     * empty national number and the phone to the bare dial code, so calling it
     * on load would wipe the number it was meant to display.
     */
    disableCountryGuess: !isExternalValue,
    onChange: (data) => {
      const digits = toDigits(data.phone);

      const dialCodeDigits = (data.country?.dialCode || "").replace(/\D/g, "");
      const dialCodeWithPlus = dialCodeDigits ? `+${dialCodeDigits}` : "";

      let nationalNumber = "";
      if (digits && dialCodeDigits) {
        if (digits === dialCodeDigits) {
          nationalNumber = "";
        } else if (digits.startsWith(dialCodeDigits)) {
          nationalNumber = digits.slice(dialCodeDigits.length);
        } else {
          nationalNumber = digits;
        }
      } else if (digits && !dialCodeDigits) {
        nationalNumber = digits;
      }

      onValuePartsChange?.({ dialCode: dialCodeWithPlus, nationalNumber });

      // When no national number is entered, the library may emit only the dial code (e.g. "+1" -> "1").
      // Treat that as "empty" so optional validation doesn't fail.
      const reported = digits && dialCodeDigits && digits === dialCodeDigits ? "" : digits;

      // Both forms are recorded so the next render recognises this component's
      // own echo whichever prop the caller happens to use.
      setLastEmitted({ full: digits, reported });

      onChange(reported);
    },
  });

  useEffect(() => {
    if (!dropdownOpen) return;
    const onDocClick = (e: MouseEvent) => {
      if (rootRef.current && !rootRef.current.contains(e.target as Node)) {
        setDropdownOpen(false);
        setSearchQuery("");
      }
    };
    const updatePosition = () => {
      if (!rootRef.current) return;

      const rootRect = rootRef.current.getBoundingClientRect();
      const parent =
        rootRef.current.parentElement || rootRef.current.offsetParent;

      // Fallback to viewport if no parent is available, but prefer parent bounds.
      const boundsRect = parent
        ? parent.getBoundingClientRect()
        : ({
            top: 0,
            bottom:
              window.innerHeight ||
              document.documentElement.clientHeight ||
              0,
          } as DOMRect);

      const spaceBelow = boundsRect.bottom - rootRect.bottom;
      const spaceAbove = rootRect.top - boundsRect.top;
      const desiredDropdownHeight = 280; // matches maxHeight below

      // Open upwards when there is not enough space below but more room above.
      if (spaceBelow < desiredDropdownHeight && spaceAbove > spaceBelow) {
        setOpenUpwards(true);
      } else {
        setOpenUpwards(false);
      }
    };

    updatePosition();
    document.addEventListener("mousedown", onDocClick);
    window.addEventListener("resize", updatePosition);
    window.addEventListener("scroll", updatePosition, true);
    return () => {
      document.removeEventListener("mousedown", onDocClick);
      window.removeEventListener("resize", updatePosition);
      window.removeEventListener("scroll", updatePosition, true);
    };
  }, [dropdownOpen]);

  return (
    <div className={className}>
      {label && (
        <label htmlFor={id} className="form-label text-sm">
          {label}
          {required ? (
            // Decorative, exactly as in `Field`: the asterisk is the visual
            // half and `aria-required` on the input is the announced half, so
            // reading "star" aloud as well would say it twice.
            <span className="lf-required" aria-hidden="true">
              *
            </span>
          ) : null}
        </label>
      )}
      <div
        ref={rootRef}
        className={`phone-input-custom position-relative d-flex align-items-center border rounded ${hasError ? "is-invalid border-danger" : ""}`}
        style={{
          minHeight: 38,
          backgroundColor: "#fff",
          borderColor: "#dee2e6",
        }}
      >
        {/* Country selector button */}
        <button
          type="button"
          className="d-flex align-items-center gap-1 px-2 py-1 border-0 bg-transparent flex-shrink-0"
          onClick={() => !disabled && setDropdownOpen((o) => !o)}
          disabled={disabled}
          aria-haspopup="listbox"
          aria-expanded={dropdownOpen}
        >
          <Image
            src={`${FLAG_URL}/${country.iso2.toUpperCase()}.svg`}
            alt={country.iso2}
            width={20}
            height={14}
            style={{ objectFit: "cover", flexShrink: 0 }}
          />
          <span
            className="text-muted small overflow-hidden text-truncate"
            style={{ minWidth: 0, maxWidth: 60 }}
          >
            +{country.dialCode}
          </span>
          <span
            className="ms-1 flex-shrink-0"
            style={{
              borderLeft: "4px solid transparent",
              borderRight: "4px solid transparent",
              borderTop: "5px solid #666",
              marginTop: 2,
            }}
          />
        </button>
        {/* Phone input */}
        <input
          ref={inputRef}
          type="tel"
          id={id}
          value={inputValue}
          onChange={handlePhoneValueChange}
          placeholder={placeholder}
          disabled={disabled}
          className={`form-control border-0 flex-grow-1 ${inputClass} ${hasError ? "is-invalid" : ""}`}
          style={{ minWidth: 0 }}
          // The error below was rendered but never announced: without
          // `aria-describedby` pointing at it, a screen reader reaching this
          // input hears a bare "Mobile number" and no reason it was rejected.
          // Before `inputProps` so a caller can still override any of them.
          aria-required={required || undefined}
          aria-invalid={hasError || undefined}
          aria-describedby={hasError ? `${id}-error` : undefined}
          {...inputProps}
        />

        {/* Searchable country dropdown */}
        {dropdownOpen && (
          <div
            className="position-absolute bg-white border rounded shadow-lg"
            style={{
              ...(openUpwards
                ? { bottom: "100%", marginBottom: 4 }
                : { top: "100%", marginTop: 4 }),
              left: 0,
              right: 0,
              maxHeight: 280,
              minWidth: 280,
              zIndex: 1050,
            }}
            role="listbox"
          >
            <div className="p-2 border-bottom">
              <input
                type="text"
                className="form-control form-control-sm"
                placeholder="Search country..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                autoFocus
              />
            </div>
            <div style={{ maxHeight: 220, overflowY: "auto" }}>
              {filteredCountries.length === 0 ? (
                <div className="p-3 text-muted small">No countries found</div>
              ) : (
                filteredCountries.map((c) => (
                  <button
                    key={c.iso2}
                    type="button"
                    className={`w-100 d-flex align-items-center gap-2 px-3 py-2 border-0 bg-white text-start ${country.iso2 === c.iso2 ? "bg-light" : ""}`}
                    style={{ fontSize: 14 }}
                    onClick={() => {
                      setCountry(c.iso2, { focusOnInput: true });
                      setDropdownOpen(false);
                      setSearchQuery("");
                    }}
                  >
                    <Image
                      src={`${FLAG_URL}/${c.iso2.toUpperCase()}.svg`}
                      alt={c.iso2}
                      width={20}
                      height={14}
                      style={{ objectFit: "cover", flexShrink: 0 }}
                      className="flex-shrink-0"
                    />
                    <span className="flex-grow-1 text-truncate">{c.name}</span>
                    <span className="text-muted">+{c.dialCode}</span>
                  </button>
                ))
              )}
            </div>
          </div>
        )}
      </div>
      {error && (
        <div className="invalid-feedback d-block" id={`${id}-error`}>
          {error}
        </div>
      )}
    </div>
  );
}

export default PhoneInput;
