'use client';

import { useState, useEffect, useRef } from 'react';
import { api, apiPaths } from '@/lib/api';

export type CountryOption = { id: number; name: string; key: string; flag?: string };

export type PhoneCountryLabels = {
  countryPlaceholder: string;
  searchCountry: string;
  noResults: string;
  /** نص الحقل الافتراضي لرقم الجوال (مثل 05xxxxxxxx) */
  phonePlaceholder?: string;
};

type Props = {
  phone: string;
  onPhoneChange: (value: string) => void;
  /** مفتاح الدولة كما في الـ API (مثل 966) بدون + */
  countryKey: string;
  onCountryKeyChange: (key: string) => void;
  /** عند تغيير الدولة المختارة (مثلاً لحفظ العلم في مسار OTP) */
  onSelectedCountry?: (country: CountryOption | null) => void;
  isRtl: boolean;
  disabled?: boolean;
  labels: PhoneCountryLabels;
  /** أيقونة جوال على يسار الحقل (اتجاه الشاشة) */
  showPhoneIcon?: boolean;
  /** نفس خلفية/ارتفاع حقول النماذج الطويلة (تسجيل، إلخ) */
  variant?: 'default' | 'form';
  /** classes إضافية للغلاف */
  className?: string;
  /** رسالة خطأ تحت الصف + إطار أحمر */
  error?: string;
};

/**
 * صف اختيار الدولة + رقم الجوال — نفس سلوك وواجهة تسجيل الدخول (قائمة دول من الـ API).
 */
export default function PhoneCountryRow({
  phone,
  onPhoneChange,
  countryKey,
  onCountryKeyChange,
  onSelectedCountry,
  isRtl,
  disabled = false,
  labels,
  showPhoneIcon = true,
  variant = 'default',
  className = '',
  error = '',
}: Props) {
  const [countries, setCountries] = useState<CountryOption[]>([]);
  const [selected, setSelected] = useState<CountryOption | null>(null);
  const [dropdownOpen, setDropdownOpen] = useState(false);
  const [search, setSearch] = useState('');
  const [loadingC, setLoadingC] = useState(true);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const searchRef = useRef<HTMLInputElement>(null);

  const isForm = variant === 'form';
  const btnBorderRound = isRtl
    ? isForm
      ? 'border-l border-gray-200/90 rounded-r-xl'
      : 'border-l border-gray-200 rounded-r-lg'
    : isForm
      ? 'border-r border-gray-200/90 rounded-l-xl'
      : 'border-r border-gray-200 rounded-l-lg';
  const dropdownPos = isRtl ? 'right-0' : 'left-0';
  const searchIconPos = isRtl ? 'right-3' : 'left-3';
  const searchInputPad = isRtl ? 'pr-9 pl-3' : 'pl-9 pr-3';
  const rowAlign = isRtl ? 'text-right' : 'text-left';

  useEffect(() => {
    let cancelled = false;
    api
      .get<CountryOption[]>(apiPaths.general.countries)
      .then((res) => {
        if (cancelled) return;
        if (res.key === 'success' && Array.isArray(res.data)) {
          const list = res.data as CountryOption[];
          setCountries(list);
          const initial =
            list.find((c) => c.key === countryKey) ?? list.find((c) => c.key === '966') ?? list[0] ?? null;
          setSelected(initial);
          onSelectedCountry?.(initial);
        }
        setLoadingC(false);
      })
      .catch(() => {
        if (!cancelled) setLoadingC(false);
      });
    return () => {
      cancelled = true;
    };
  }, []);

  useEffect(() => {
    if (countries.length === 0) return;
    const match = countries.find((c) => c.key === countryKey);
    if (match && match.id !== selected?.id) {
      setSelected(match);
    }
  }, [countryKey, countries, selected?.id]);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
        setDropdownOpen(false);
        setSearch('');
      }
    };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  useEffect(() => {
    if (dropdownOpen) setTimeout(() => searchRef.current?.focus(), 50);
  }, [dropdownOpen]);

  const filtered = search
    ? countries.filter((c) => c.name.includes(search) || c.key.includes(search))
    : countries;

  const hasErr = Boolean(error);
  const wrapClass = isForm
    ? `flex items-stretch min-h-[48px] border rounded-xl shadow-sm overflow-visible transition-all ${
        !isRtl ? 'flex-row-reverse' : ''
      } ${
        hasErr
          ? 'border-red-500 ring-1 ring-red-500/30 bg-[#fef2f2] focus-within:ring-2 focus-within:ring-red-500/25 focus-within:border-red-500'
          : 'border-gray-200 bg-[#f8fafc] focus-within:ring-2 focus-within:ring-[#1e3a5f]/20 focus-within:border-[#1e3a5f]/35'
      }`
    : `flex items-center border rounded-xl overflow-visible transition-all ${
        !isRtl ? 'flex-row-reverse' : ''
      } ${
        hasErr
          ? 'border-red-500 ring-1 ring-red-500/30 bg-red-50/50 focus-within:ring-2 focus-within:ring-red-500/25 focus-within:border-red-500'
          : 'border-gray-200 bg-white focus-within:ring-2 focus-within:ring-[#1e3a5f]/25 focus-within:border-[#1e3a5f]/40'
      }`;

  return (
    <div className="w-full">
      <div className={`${wrapClass} ${className}`.trim()}>
      <div className="relative flex flex-shrink-0 self-stretch" ref={dropdownRef}>
        <button
          type="button"
          onClick={() => setDropdownOpen(!dropdownOpen)}
          disabled={loadingC || disabled}
          className={`flex items-center gap-2 min-h-[48px] px-3 sm:px-3.5 ${btnBorderRound} ${
            isForm ? 'bg-white/90 hover:bg-white' : 'bg-gray-50 hover:bg-gray-100'
          } transition-colors cursor-pointer disabled:opacity-60`}
        >
          {loadingC ? (
            <span className="w-4 h-4 border-2 border-gray-300 border-t-blue-500 rounded-full animate-spin" />
          ) : selected ? (
            <>
              {selected.flag ? (
                <img src={selected.flag} alt="" className="w-5 h-3.5 object-cover rounded-sm flex-shrink-0" />
              ) : (
                <i className="ri-global-line text-gray-400 text-sm"></i>
              )}
              <span className="text-sm font-semibold text-gray-700 tabular-nums" dir="ltr">
                +{selected.key}
              </span>
            </>
          ) : (
            <span className="text-sm text-gray-400">{labels.countryPlaceholder}</span>
          )}
          <i
            className={`ri-arrow-down-s-line text-gray-400 text-sm transition-transform duration-200 ${
              dropdownOpen ? 'rotate-180' : ''
            }`}
          ></i>
        </button>

        {dropdownOpen && (
          <div
            className={`absolute top-full ${dropdownPos} mt-1.5 w-72 bg-white border border-gray-200 rounded-xl shadow-2xl z-50 overflow-hidden`}
          >
            <div className="p-2.5 border-b border-gray-100 bg-gray-50">
              <div className="relative">
                <i
                  className={`ri-search-line absolute ${searchIconPos} top-1/2 -translate-y-1/2 text-gray-400 text-sm`}
                ></i>
                <input
                  ref={searchRef}
                  type="text"
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  placeholder={labels.searchCountry}
                  className={`w-full ${searchInputPad} py-2 text-sm bg-white border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400`}
                />
              </div>
            </div>

            <div className="max-h-52 overflow-y-auto">
              {filtered.length === 0 ? (
                <div className="py-6 text-center text-sm text-gray-400">
                  <i className="ri-search-line text-2xl block mb-1"></i>
                  {labels.noResults}
                </div>
              ) : (
                filtered.map((c) => (
                  <button
                    key={c.id}
                    type="button"
                    onClick={() => {
                      setSelected(c);
                      onCountryKeyChange(c.key);
                      onSelectedCountry?.(c);
                      setDropdownOpen(false);
                      setSearch('');
                    }}
                    className={`w-full flex items-center gap-3 px-4 py-2.5 text-sm ${rowAlign} transition-colors cursor-pointer ${
                      selected?.id === c.id ? 'bg-blue-50 text-blue-700' : 'hover:bg-gray-50 text-gray-700'
                    }`}
                  >
                    {c.flag ? (
                      <img src={c.flag} alt="" className="w-6 h-4 object-cover rounded-sm flex-shrink-0" />
                    ) : (
                      <i className="ri-global-line text-gray-400 w-6 text-center"></i>
                    )}
                    <span className="flex-1 truncate font-medium">{c.name}</span>
                    <span className="text-gray-400 font-mono tabular-nums flex-shrink-0" dir="ltr">
                      +{c.key}
                    </span>
                    {selected?.id === c.id && <i className="ri-check-line text-blue-600 flex-shrink-0"></i>}
                  </button>
                ))
              )}
            </div>
          </div>
        )}
      </div>

      <input
        type="tel"
        value={phone}
        onChange={(e) => onPhoneChange(e.target.value)}
        placeholder={labels.phonePlaceholder ?? '5xxxxxxxx'}
        className={`flex-1 min-w-0 bg-transparent focus:outline-none placeholder:text-gray-400 ${
          isForm ? 'px-4 py-3.5 text-sm text-gray-900' : 'px-3 py-3 text-sm'
        }`}
        required
        disabled={disabled}
        dir="ltr"
        autoComplete="tel-national"
      />
      {showPhoneIcon && (
        <div
          className={`flex items-center justify-center flex-shrink-0 ${isForm ? 'ps-1 pe-4' : 'pl-1 pr-3'}`}
          aria-hidden
        >
          <i className={`ri-smartphone-line text-[#1e3a5f]/45 ${isForm ? 'text-xl' : 'text-lg'}`} />
        </div>
      )}
    </div>
      {error ? (
        <p className="mt-1.5 text-sm text-red-600" role="alert">
          {error}
        </p>
      ) : null}
    </div>
  );
}
