"use client";

import { useState, useMemo, useRef, useLayoutEffect } from "react";
import { createPortal } from "react-dom";
import { useLanguage } from "@/lib/language-context";

const COUNTRY_CODES: { code: string; dial: string; flag: string }[] = [
  { code: "EG", dial: "+20", flag: "🇪🇬" },
  { code: "SA", dial: "+966", flag: "🇸🇦" },
  { code: "AE", dial: "+971", flag: "🇦🇪" },
  { code: "KW", dial: "+965", flag: "🇰🇼" },
  { code: "QA", dial: "+974", flag: "🇶🇦" },
  { code: "BH", dial: "+973", flag: "🇧🇭" },
  { code: "OM", dial: "+968", flag: "🇴🇲" },
  { code: "US", dial: "+1", flag: "🇺🇸" },
  { code: "GB", dial: "+44", flag: "🇬🇧" },
  { code: "JO", dial: "+962", flag: "🇯🇴" },
  { code: "LB", dial: "+961", flag: "🇱🇧" },
  { code: "SY", dial: "+963", flag: "🇸🇾" },
  { code: "IQ", dial: "+964", flag: "🇮🇶" },
  { code: "YE", dial: "+967", flag: "🇾🇪" },
  { code: "SD", dial: "+249", flag: "🇸🇩" },
  { code: "LY", dial: "+218", flag: "🇱🇾" },
  { code: "TN", dial: "+216", flag: "🇹🇳" },
  { code: "DZ", dial: "+213", flag: "🇩🇿" },
  { code: "MA", dial: "+212", flag: "🇲🇦" },
];

function parsePhone(value: string): { dial: string; local: string } {
  const trimmed = (value || "").trim();
  if (!trimmed) return { dial: "+20", local: "" };
  const withPlus = trimmed.startsWith("+") ? trimmed : `+${trimmed}`;
  for (const { dial } of COUNTRY_CODES) {
    if (withPlus === dial || withPlus.startsWith(dial)) {
      const local = withPlus.slice(dial.length).replace(/\D/g, "");
      return { dial, local };
    }
  }
  return { dial: "+20", local: trimmed.replace(/\D/g, "") };
}

function formatFullPhone(dial: string, local: string): string {
  const digits = local.replace(/\D/g, "");
  if (!digits) return dial;
  return `${dial}${digits}`;
}

interface PhoneInputProps {
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  required?: boolean;
  className?: string;
  id?: string;
}

export default function PhoneInput({
  value,
  onChange,
  placeholder = "1234567890",
  required,
  className = "",
  id,
}: PhoneInputProps) {
  const { isRtl } = useLanguage();
  const { dial, local } = useMemo(() => parsePhone(value), [value]);
  const [open, setOpen] = useState(false);
  const [dropdownStyle, setDropdownStyle] = useState<{ top: number; left: number; minWidth: number } | null>(null);
  const triggerRef = useRef<HTMLButtonElement>(null);

  const current =
    COUNTRY_CODES.find((c) => c.dial === dial) ?? COUNTRY_CODES[0];

  const handleDialChange = (newDial: string) => {
    setOpen(false);
    onChange(formatFullPhone(newDial, local));
  };

  const handleLocalChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const v = e.target.value.replace(/\D/g, "");
    onChange(formatFullPhone(dial, v));
  };

  // Position dropdown when opening (and on scroll/resize while open)
  useLayoutEffect(() => {
    if (!open || !triggerRef.current) {
      setDropdownStyle(null);
      return;
    }
    const update = () => {
      if (!triggerRef.current) return;
      const rect = triggerRef.current.getBoundingClientRect();
      setDropdownStyle({
        top: rect.bottom + 4,
        left: isRtl ? rect.right - 224 : rect.left,
        minWidth: Math.max(rect.width, 224),
      });
    };
    update();
    window.addEventListener("scroll", update, true);
    window.addEventListener("resize", update);
    return () => {
      window.removeEventListener("scroll", update, true);
      window.removeEventListener("resize", update);
    };
  }, [open, isRtl]);

  const inputBase =
    "w-full border-0 bg-transparent py-0 text-gray-900 placeholder-gray-400 focus:ring-0 focus:outline-none text-sm";

  const dropdownEl =
    open && typeof document !== "undefined" ? (
      <>
        <div
          className="fixed inset-0 z-[100]"
          aria-hidden
          onClick={() => setOpen(false)}
        />
        {dropdownStyle && (
        <ul
          role="listbox"
          className="fixed z-[101] w-56 min-w-[14rem] max-h-60 overflow-auto rounded-xl border-2 border-gray-200 bg-white shadow-lg py-1"
          style={{
            top: dropdownStyle.top,
            left: dropdownStyle.left,
            minWidth: dropdownStyle.minWidth,
          }}
        >
          {COUNTRY_CODES.map((c) => (
            <li
              key={c.code}
              role="option"
              aria-selected={c.dial === dial}
              onMouseDown={(e) => e.preventDefault()}
              onClick={() => handleDialChange(c.dial)}
              className="flex items-center gap-2 px-3 py-2.5 cursor-pointer hover:bg-gray-50 text-sm"
            >
              <span className="text-lg">{c.flag}</span>
              <span className="font-medium tabular-nums">{c.dial}</span>
            </li>
          ))}
        </ul>
        )}
      </>
    ) : null;

  return (
    <div
      className={`flex rounded-xl border-2 border-gray-200 bg-white focus-within:border-[color:var(--color-primary)] focus-within:shadow-[0_0_0_3px_color-mix(in_srgb,var(--color-primary)_15%,transparent)] transition-all ${className} ${isRtl ? "flex-row-reverse" : ""}`}
    >
      {/* Country code selector - in RTL appears on the right */}
      <div className={`relative flex-shrink-0 rounded-l-xl ${isRtl ? "rounded-l-none rounded-r-xl border-l border-gray-200" : "border-r border-gray-200"}`}>
        <button
          ref={triggerRef}
          type="button"
          onClick={() => setOpen((o) => !o)}
          className="flex items-center justify-center gap-2 px-4 py-3 text-gray-700 hover:bg-gray-50 transition-colors min-w-[7rem] sm:min-w-[120px]"
          aria-haspopup="listbox"
          aria-expanded={open}
          aria-label="Country code"
        >
          <span className="text-xl leading-none" aria-hidden>
            {current.flag}
          </span>
          <span className="font-medium text-sm tabular-nums">
            {current.dial}
          </span>
          <svg
            className={`w-4 h-4 text-gray-400 transition-transform ${
              open ? "rotate-180" : ""
            }`}
            fill="none"
            viewBox="0 0 24 24"
            stroke="currentColor"
            strokeWidth={2}
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M19 9l-7 7-7-7"
            />
          </svg>
        </button>
      </div>
      {typeof document !== "undefined" && dropdownEl && createPortal(dropdownEl, document.body)}
      {/* Phone number input */}
      <div className={`flex flex-1 min-w-0 items-center gap-2 py-2.5 rounded-r-xl ${isRtl ? "rounded-r-none rounded-l-xl pr-3 pl-3.5" : "pl-3 pr-3.5"}`}>
        <svg
          className="w-5 h-5 text-gray-400 flex-shrink-0"
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
          strokeWidth={2}
        >
          <path
            strokeLinecap="round"
            strokeLinejoin="round"
            d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z"
          />
        </svg>
        <input
          id={id}
          type="tel"
          inputMode="numeric"
          autoComplete="tel-national"
          value={local}
          onChange={handleLocalChange}
          placeholder={placeholder}
          required={required}
          className={inputBase}
          dir="ltr"
        />
      </div>
    </div>
  );
}
