"use client";

import * as React from "react";
import { Input } from "@/components/ui/input";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
} from "@/components/ui/select";
import { CountryFlag } from "@/components/ui/country-flag";
import {
  DEFAULT_PHONE_DIAL,
  PHONE_COUNTRIES,
  joinPhoneValue,
  splitPhoneValue,
  type PhoneCountry,
} from "@/lib/auth-identity";
import { cn } from "@/lib/utils";

export type PhoneInputProps = {
  value: string;
  onChange: (fullPhone: string) => void;
  id?: string;
  name?: string;
  required?: boolean;
  disabled?: boolean;
  className?: string;
  inputClassName?: string;
  placeholder?: string;
  autoComplete?: string;
};

function countryForDial(dial: string): PhoneCountry {
  return (
    PHONE_COUNTRIES.find((c) => c.dial === dial) ||
    PHONE_COUNTRIES.find((c) => c.dial === DEFAULT_PHONE_DIAL)!
  );
}

/**
 * Mobile number field with country dial-code select.
 * Emits a combined value like `+923034642582`.
 */
export function PhoneInput({
  value,
  onChange,
  id,
  name,
  required,
  disabled,
  className,
  inputClassName,
  placeholder = "3XXXXXXXXX",
  autoComplete = "tel-national",
}: PhoneInputProps) {
  const parsed = splitPhoneValue(value);
  const [countryCode, setCountryCode] = React.useState(
    () => countryForDial(parsed.dial).code,
  );
  const [national, setNational] = React.useState(parsed.national);

  React.useEffect(() => {
    const next = splitPhoneValue(value);
    setNational(next.national);
    setCountryCode((prev) => {
      const prevCountry = PHONE_COUNTRIES.find((c) => c.code === prev);
      if (prevCountry?.dial === next.dial) return prev;
      return countryForDial(next.dial).code;
    });
  }, [value]);

  const dial =
    PHONE_COUNTRIES.find((c) => c.code === countryCode)?.dial || DEFAULT_PHONE_DIAL;

  const emit = (nextDial: string, nextNational: string) => {
    onChange(joinPhoneValue(nextDial, nextNational));
  };

  return (
    <div className={cn("flex min-w-0 gap-2", className)}>
      <Select
        value={countryCode}
        disabled={disabled}
        onValueChange={(code) => {
          const country = PHONE_COUNTRIES.find((c) => c.code === code);
          const nextDial = country?.dial || DEFAULT_PHONE_DIAL;
          setCountryCode(code);
          emit(nextDial, national);
        }}
      >
        <SelectTrigger
          className="w-[6.5rem] shrink-0 border-input bg-gray-100 px-2"
          aria-label="Country code"
        >
          <span className="flex items-center gap-1.5">
            <CountryFlag code={countryCode} />
            <span className="tabular-nums">+{dial}</span>
          </span>
        </SelectTrigger>
        <SelectContent className="max-h-64">
          {PHONE_COUNTRIES.map((c) => (
            <SelectItem key={c.code} value={c.code}>
              <span className="flex items-center gap-2">
                <CountryFlag code={c.code} />
                <span>
                  +{c.dial} · {c.name}
                </span>
              </span>
            </SelectItem>
          ))}
        </SelectContent>
      </Select>
      <Input
        id={id}
        name={name}
        type="tel"
        inputMode="tel"
        autoComplete={autoComplete}
        required={required}
        disabled={disabled}
        placeholder={placeholder}
        value={national}
        className={cn("min-w-0 flex-1", inputClassName)}
        onChange={(e) => {
          const next = e.target.value.replace(/\D/g, "");
          setNational(next);
          emit(dial, next);
        }}
      />
    </div>
  );
}

export default PhoneInput;
