"use client"

import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Card } from "@/components/ui/card"
import { Mail } from "lucide-react"
import { ContactInformationSchema, type ContactInformation as ContactInformationType } from "@/lib/types/checkout"
import { useEffect, useCallback, useRef } from "react"

interface ContactInformationProps {
  onChange?: (data: ContactInformationType) => void
  defaultValues?: Partial<ContactInformationType>
  orderId?: number
}

/**
 * Format digits into (XXX) XXX-XXXX
 * Accepts any input — strips non-digits, handles partial input
 */
function formatUSPhone(value: string): string {
  const digits = value.replace(/\D/g, "")
  const local = digits.startsWith("1") && digits.length > 10 ? digits.slice(1) : digits
  const capped = local.slice(0, 10)

  if (capped.length === 0) return ""
  if (capped.length <= 3) return `(${capped}`
  if (capped.length <= 6) return `(${capped.slice(0, 3)}) ${capped.slice(3)}`
  return `(${capped.slice(0, 3)}) ${capped.slice(3, 6)}-${capped.slice(6)}`
}

export function ContactInformation({ onChange, defaultValues, orderId }: ContactInformationProps) {
  const onChangeRef = useRef(onChange)
  onChangeRef.current = onChange

  const {
    register,
    formState: { errors },
    watch,
  } = useForm<ContactInformationType>({
    resolver: zodResolver(ContactInformationSchema),
    mode: "onChange",
    defaultValues: defaultValues || {
      email: "",
      phone: "",
    },
  })

  // Watch all fields and validate inline to notify parent immediately
  const allValues = watch()

  useEffect(() => {
    const cb = onChangeRef.current
    if (!cb) return

    const result = ContactInformationSchema.safeParse(allValues)
    if (result.success) {
      cb(result.data)
    } else {
      cb(null as unknown as ContactInformationType)
    }
  }, [allValues.email, allValues.phone])

  // Register phone with custom onChange that formats then feeds back into RHF
  const { onChange: rhfPhoneOnChange, ...phoneRest } = register("phone")

  const handlePhoneChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      // Format the value, write it back to the input, then let RHF process it
      e.target.value = formatUSPhone(e.target.value)
      rhfPhoneOnChange(e)
    },
    [rhfPhoneOnChange],
  )

  return (
    <Card className="p-10 shadow-float border-border/50 focus-within:shadow-elevated transition-all duration-300">
      <div className="mb-8">
        <div className="flex items-center gap-3 mb-3">
          <div className="h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center">
            <Mail className="h-5 w-5 text-primary" />
          </div>
          <h2 className="text-2xl font-bold text-foreground tracking-tight">
            {orderId ? `Order #${orderId}` : "Identity"}
          </h2>
        </div>
        <p className="text-sm text-muted-foreground">How we'll reach you</p>
      </div>

      <div className="space-y-6">
        <div className="space-y-3">
          <Label htmlFor="email" className="text-sm font-medium text-foreground">
            Email Address
          </Label>
          <div className="relative">
            <Input
              id="email"
              type="email"
              placeholder="you@example.com"
              className="h-14 text-base pl-11 focus-glow transition-all"
              autoComplete="email"
              {...register("email")}
              aria-invalid={errors.email ? "true" : "false"}
            />
            <Mail className="absolute left-4 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          </div>
          {errors.email && <p className="text-sm text-destructive mt-1">{errors.email.message}</p>}
        </div>

        <div className="space-y-3">
          <Label htmlFor="phone" className="text-sm font-medium text-foreground">
            Phone Number
          </Label>
          <div className="relative flex">
            {/* US Flag + +1 prefix */}
            <div className="flex items-center gap-1.5 h-14 px-3.5 rounded-l-md border border-r-0 border-input bg-muted/50 select-none shrink-0">
              <span className="text-lg leading-none" role="img" aria-label="US flag">🇺🇸</span>
              <span className="text-sm font-medium text-foreground">+1</span>
            </div>
            <Input
              id="phone"
              type="tel"
              placeholder="(555) 000-0000"
              className="h-14 text-base rounded-l-none focus-glow transition-all"
              autoComplete="tel-national"
              {...phoneRest}
              onChange={handlePhoneChange}
              aria-invalid={errors.phone ? "true" : "false"}
            />
          </div>
          {errors.phone && <p className="text-sm text-destructive mt-1">{errors.phone.message}</p>}
        </div>
      </div>
    </Card>
  )
}
