"use client";

import {
  InputGroup,
  InputGroupAddon,
  InputGroupInput,
  InputGroupText,
} from "@/components/ui/input-group";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { cn } from "@/lib/utils";

import { PHONE_COUNTRIES } from "./constants";

type PhoneInputProps = {
  countryCode: string;
  phone: string;
  onCountryChange: (code: string) => void;
  onPhoneChange: (phone: string) => void;
  id?: string;
  className?: string;
  invalid?: boolean;
};

function sanitizePhone(value: string) {
  return value.replace(/[^0-9.]/g, "").replace(/(\..*)\./g, "$1");
}

export function PhoneInput({
  countryCode,
  phone,
  onCountryChange,
  onPhoneChange,
  id = "phone",
  className,
  invalid,
}: PhoneInputProps) {
  const selected = PHONE_COUNTRIES.find((c) => c.code === countryCode) ?? PHONE_COUNTRIES[0];

  return (
    <InputGroup className={cn("h-9", invalid && "border-destructive ring-destructive/20", className)}>
      <InputGroupAddon align="inline-start" className="shrink-0 border-r border-input pr-1 pl-1">
        <Select value={countryCode} onValueChange={onCountryChange}>
          <SelectTrigger className="h-7 w-[108px] border-0 bg-transparent shadow-none focus:ring-0">
            <SelectValue>
              <span className="flex items-center gap-1.5 text-sm">
                <span aria-hidden>{selected.flag}</span>
                <span className="text-muted-foreground">{selected.dial}</span>
              </span>
            </SelectValue>
          </SelectTrigger>
          <SelectContent>
            {PHONE_COUNTRIES.map((c) => (
              <SelectItem key={c.code} value={c.code}>
                <span className="flex items-center gap-2">
                  <span>{c.flag}</span>
                  <span>{c.label}</span>
                  <span className="text-muted-foreground">{c.dial}</span>
                </span>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </InputGroupAddon>
      <InputGroupInput
        id={id}
        type="tel"
        placeholder="e.g. 6 701 5757"
        value={phone}
        onChange={(e) => onPhoneChange(sanitizePhone(e.target.value))}
      />
      <InputGroupAddon align="inline-end" className="sr-only">
        <InputGroupText>Mobile</InputGroupText>
      </InputGroupAddon>
    </InputGroup>
  );
}
