"use client"

import { forwardRef } from "react"
import { Input } from "@/components/ui/input"
import { cn } from "@/lib/utils"

export interface PhoneInputProps
  extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'onChange'> {
  onChange?: (value: string) => void
}

const PhoneInput = forwardRef<HTMLInputElement, PhoneInputProps>(
  ({ className, onChange, ...props }, ref) => {
    const formatPhoneNumber = (value: string) => {
      // Remove all non-digits
      const phoneNumber = value.replace(/\D/g, '')
      
      // Format based on length
      if (phoneNumber.length === 0) return ''
      if (phoneNumber.length <= 3) return `(${phoneNumber}`
      if (phoneNumber.length <= 6) return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(3)}`
      return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(3, 6)}-${phoneNumber.slice(6, 10)}`
    }

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      const formatted = formatPhoneNumber(e.target.value)
      
      if (onChange) {
        onChange(formatted)
      }
    }

    return (
      <Input
        type="tel"
        className={cn(className)}
        onChange={handleChange}
        placeholder="(555) 123-4567"
        maxLength={14}
        ref={ref}
        {...props}
      />
    )
  }
)
PhoneInput.displayName = "PhoneInput"

export { PhoneInput }

// Utility function to validate phone numbers
export const isValidPhoneNumber = (phone: string): boolean => {
  const digits = phone.replace(/\D/g, '')
  return digits.length === 10
}

// Utility function to get clean phone number (digits only)
export const getCleanPhoneNumber = (phone: string): string => {
  return phone.replace(/\D/g, '')
}
