"use client"

import React, { useState, useRef, useEffect } from "react"
import { cn } from "../../lib/utils"
import { Input } from "../ui/input"
import { Label } from "../ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../ui/select"
import { Phone, Globe, Check, X } from "lucide-react"
import { motion, AnimatePresence } from "framer-motion"

// Ülke kodları ve bayrakları
const countries = [
  { code: 'US', name: 'United States', dialCode: '+1', flag: '🇺🇸', format: '(xxx) xxx-xxxx' },
  { code: 'GB', name: 'United Kingdom', dialCode: '+44', flag: '🇬🇧', format: 'xxxx xxxxxx' },
  { code: 'TR', name: 'Turkey', dialCode: '+90', flag: '🇹🇷', format: '(xxx) xxx xx xx' },
  { code: 'DE', name: 'Germany', dialCode: '+49', flag: '🇩🇪', format: 'xxx xxxxxxxx' },
  { code: 'FR', name: 'France', dialCode: '+33', flag: '🇫🇷', format: 'x xx xx xx xx' },
  { code: 'IT', name: 'Italy', dialCode: '+39', flag: '🇮🇹', format: 'xxx xxxxxxx' },
  { code: 'ES', name: 'Spain', dialCode: '+34', flag: '🇪🇸', format: 'xxx xxx xxx' },
  { code: 'CN', name: 'China', dialCode: '+86', flag: '🇨🇳', format: 'xxx xxxx xxxx' },
  { code: 'JP', name: 'Japan', dialCode: '+81', flag: '🇯🇵', format: 'xx xxxx xxxx' },
  { code: 'KR', name: 'South Korea', dialCode: '+82', flag: '🇰🇷', format: 'xx xxxx xxxx' },
  { code: 'IN', name: 'India', dialCode: '+91', flag: '🇮🇳', format: 'xxxxx xxxxx' },
  { code: 'BR', name: 'Brazil', dialCode: '+55', flag: '🇧🇷', format: '(xx) xxxxx-xxxx' },
  { code: 'MX', name: 'Mexico', dialCode: '+52', flag: '🇲🇽', format: 'xxx xxx xxxx' },
  { code: 'CA', name: 'Canada', dialCode: '+1', flag: '🇨🇦', format: '(xxx) xxx-xxxx' },
  { code: 'AU', name: 'Australia', dialCode: '+61', flag: '🇦🇺', format: 'xxx xxx xxx' },
  { code: 'RU', name: 'Russia', dialCode: '+7', flag: '🇷🇺', format: '(xxx) xxx-xx-xx' },
  { code: 'NL', name: 'Netherlands', dialCode: '+31', flag: '🇳🇱', format: 'x xxxxxxxx' },
  { code: 'SE', name: 'Sweden', dialCode: '+46', flag: '🇸🇪', format: 'xx xxx xx xx' },
  { code: 'NO', name: 'Norway', dialCode: '+47', flag: '🇳🇴', format: 'xxx xx xxx' },
  { code: 'FI', name: 'Finland', dialCode: '+358', flag: '🇫🇮', format: 'xx xxxxxxx' }
]

export interface PhoneNumberInputProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'value'> {
  value?: {
    country: string
    number: string
  }
  onChange?: (value: { country: string; number: string; fullNumber: string; isValid: boolean }) => void
  defaultCountry?: string
  countries?: typeof countries
  showFlags?: boolean
  showDialCode?: boolean
  autoFormat?: boolean
  validateOnChange?: boolean
  showValidationIcon?: boolean
  label?: string
  error?: string
  helperText?: string
  required?: boolean
  className?: string
  inputClassName?: string
  selectClassName?: string
  labelClassName?: string
  errorClassName?: string
  allowInternationalFormat?: boolean
}

// Telefon numarası formatlama
function formatPhoneNumber(number: string, format: string): string {
  if (!number || !format) return ''
  const cleaned = number.replace(/\D/g, '')
  let formatted = ''
  let digitIndex = 0
  
  for (let i = 0; i < format.length && digitIndex < cleaned.length; i++) {
    if (format[i] === 'x') {
      formatted += cleaned[digitIndex]
      digitIndex++
    } else {
      formatted += format[i]
    }
  }
  
  return formatted
}

// Telefon numarası doğrulama
function validatePhoneNumber(number: string, countryCode: string): boolean {
  if (!number || !countryCode) return false
  const cleaned = number.replace(/\D/g, '')
  const country = countries.find(c => c.code === countryCode)
  
  if (!country) return false
  
  // Format'taki x sayısını say
  const expectedLength = country.format.split('').filter(c => c === 'x').length
  
  return cleaned.length === expectedLength
}

// Uluslararası format dönüştürme
function toInternationalFormat(countryCode: string, phoneNumber: string): string {
  if (!countryCode || !phoneNumber) return ''
  const country = countries.find(c => c.code === countryCode)
  if (!country) return phoneNumber
  
  const cleaned = phoneNumber.replace(/\D/g, '')
  return `${country.dialCode}${cleaned}`
}

export const MoonUIPhoneNumberInputPro = React.forwardRef<HTMLDivElement, PhoneNumberInputProps>(({
  value = { country: 'US', number: '' },
  onChange,
  defaultCountry = 'US',
  countries: customCountries,
  showFlags = true,
  showDialCode = true,
  autoFormat = true,
  validateOnChange = true,
  showValidationIcon = true,
  label,
  error,
  helperText,
  required,
  className,
  inputClassName,
  selectClassName,
  labelClassName,
  errorClassName,
  disabled,
  allowInternationalFormat = true,
  ...props
}, ref) => {
  const [isValid, setIsValid] = useState(false)
  const [isFocused, setIsFocused] = useState(false)
  const inputRef = useRef<HTMLInputElement>(null)
  
  const countryList = customCountries || countries
  const selectedCountry = countryList.find(c => c.code === value.country) || countryList[0]

  // Doğrulama
  useEffect(() => {
    if (validateOnChange && value.number) {
      const valid = validatePhoneNumber(value.number, value.country)
      setIsValid(valid)
    }
  }, [value, validateOnChange])

  const handleCountryChange = (countryCode: string) => {
    const fullNumber = allowInternationalFormat 
      ? toInternationalFormat(countryCode, value.number)
      : value.number
      
    onChange?.({
      country: countryCode,
      number: value.number,
      fullNumber,
      isValid: validatePhoneNumber(value.number, countryCode)
    })
  }

  const handleNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    let newValue = e.target.value
    
    if (autoFormat) {
      // Sadece sayıları al
      const cleaned = newValue.replace(/\D/g, '')
      // Format uygula
      newValue = formatPhoneNumber(cleaned, selectedCountry.format)
    }
    
    const valid = validatePhoneNumber(newValue, value.country)
    const fullNumber = allowInternationalFormat 
      ? toInternationalFormat(value.country, newValue)
      : newValue
    
    onChange?.({
      country: value.country,
      number: newValue,
      fullNumber,
      isValid: valid
    })
  }

  const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
    if (!autoFormat) return
    
    e.preventDefault()
    const pastedText = e.clipboardData.getData('text')
    const cleaned = pastedText.replace(/\D/g, '')
    const formatted = formatPhoneNumber(cleaned, selectedCountry.format)
    
    const valid = validatePhoneNumber(formatted, value.country)
    const fullNumber = allowInternationalFormat 
      ? toInternationalFormat(value.country, formatted)
      : formatted
    
    onChange?.({
      country: value.country,
      number: formatted,
      fullNumber,
      isValid: valid
    })
  }

  return (
    <div ref={ref} className={cn("space-y-2", className)} {...props}>
      {label && (
        <Label htmlFor="phone-number" className={labelClassName}>
          {label}
          {required && <span className="text-destructive ml-1">*</span>}
        </Label>
      )}
      
      <div className="flex gap-2">
        {/* Ülke Seçici */}
        <Select
          value={value.country}
          onValueChange={handleCountryChange}
          disabled={disabled}
        >
          <SelectTrigger 
            className={cn(
              "w-[140px]",
              error && "border-destructive",
              selectClassName
            )}
          >
            <SelectValue>
              <div className="flex items-center gap-2">
                {showFlags && <span className="text-lg">{selectedCountry.flag}</span>}
                {showDialCode && <span className="text-sm">{selectedCountry.dialCode}</span>}
                {!showFlags && !showDialCode && <span className="text-sm">{selectedCountry.code}</span>}
              </div>
            </SelectValue>
          </SelectTrigger>
          <SelectContent>
            {countryList.map((country) => (
              <SelectItem key={country.code} value={country.code}>
                <div className="flex items-center gap-2">
                  {showFlags && <span className="text-lg">{country.flag}</span>}
                  <span className="text-sm">{country.name}</span>
                  {showDialCode && <span className="text-muted-foreground text-sm">{country.dialCode}</span>}
                </div>
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        {/* Telefon Numarası Input */}
        <div className="relative flex-1">
          <Input
            ref={inputRef}
            id="phone-number"
            type="tel"
            value={value.number}
            onChange={handleNumberChange}
            onPaste={handlePaste}
            onFocus={() => setIsFocused(true)}
            onBlur={() => setIsFocused(false)}
            placeholder={selectedCountry?.format?.replace(/x/g, '•') || 'Enter phone number'}
            className={cn(
              "pr-10",
              error && "border-destructive",
              inputClassName
            )}
            disabled={disabled}
          />
          
          {/* Doğrulama İkonu */}
          {showValidationIcon && value.number && (
            <div className="absolute right-3 top-1/2 -translate-y-1/2">
              <AnimatePresence mode="wait">
                {isValid ? (
                  <motion.div
                    key="valid"
                    initial={{ scale: 0, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    exit={{ scale: 0, opacity: 0 }}
                    transition={{ duration: 0.2 }}
                  >
                    <Check className="w-4 h-4 text-green-500" />
                  </motion.div>
                ) : (
                  <motion.div
                    key="invalid"
                    initial={{ scale: 0, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    exit={{ scale: 0, opacity: 0 }}
                    transition={{ duration: 0.2 }}
                  >
                    <X className="w-4 h-4 text-destructive" />
                  </motion.div>
                )}
              </AnimatePresence>
            </div>
          )}
        </div>
      </div>

      {/* Helper Text veya Error */}
      {(error || helperText) && (
        <AnimatePresence mode="wait">
          {error ? (
            <motion.p
              key="error"
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              className={cn("text-sm text-destructive", errorClassName)}
            >
              {error}
            </motion.p>
          ) : (
            <motion.p
              key="helper"
              initial={{ opacity: 0, height: 0 }}
              animate={{ opacity: 1, height: 'auto' }}
              exit={{ opacity: 0, height: 0 }}
              className="text-sm text-muted-foreground"
            >
              {helperText}
            </motion.p>
          )}
        </AnimatePresence>
      )}

      {/* Uluslararası Format Gösterimi */}
      {allowInternationalFormat && value.number && isValid && (
        <motion.div
          initial={{ opacity: 0, y: -10 }}
          animate={{ opacity: 1, y: 0 }}
          className="flex items-center gap-2 text-sm text-muted-foreground"
        >
          <Globe className="w-4 h-4" />
          <span>International: {toInternationalFormat(value.country, value.number)}</span>
        </motion.div>
      )}
    </div>
  )
})

MoonUIPhoneNumberInputPro.displayName = "MoonUIPhoneNumberInputPro"

// Ülke listesini de export edelim
export { countries as phoneCountries }