"use client"

import { useForm, Controller } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Card } from "@/components/ui/card"
import { MapPin } from "lucide-react"
import { BillingAddressSchema, type BillingAddress as BillingAddressType } from "@/lib/types/checkout"
import { US_STATES } from "@/lib/us-states"
import { useEffect } from "react"

interface BillingAddressProps {
  onChange?: (data: BillingAddressType) => void
  defaultValues?: Partial<BillingAddressType>
}

export function BillingAddress({ onChange, defaultValues }: BillingAddressProps) {
  const {
    register,
    control,
    formState: { errors },
    watch,
  } = useForm<BillingAddressType>({
    resolver: zodResolver(BillingAddressSchema),
    mode: "onChange",
    defaultValues: defaultValues || {
      first_name: "",
      last_name: "",
      address_1: "",
      address_2: "",
      city: "",
      state: "",
      postcode: "",
      country: "US",
    },
  })

  // Watch form changes and notify parent using subscription
  useEffect(() => {
    if (!onChange) return

    const subscription = watch((value) => {
      onChange(value as BillingAddressType)
    })
    return () => subscription.unsubscribe()
  }, [watch, onChange])
  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">
            <MapPin className="h-5 w-5 text-primary" />
          </div>
          <h2 className="text-2xl font-bold text-foreground tracking-tight">Billing Address</h2>
        </div>
        <p className="text-sm text-muted-foreground">Where your payment originates</p>
      </div>

      <div className="space-y-6">
        <div className="grid gap-6 sm:grid-cols-2">
          <div className="space-y-3">
            <Label htmlFor="first_name" className="text-sm font-medium text-foreground">
              First Name
            </Label>
            <Input
              id="first_name"
              type="text"
              placeholder="John"
              className="h-14 text-base focus-glow transition-all"
              autoComplete="given-name"
              {...register("first_name")}
              aria-invalid={errors.first_name ? "true" : "false"}
            />
            {errors.first_name && <p className="text-sm text-destructive mt-1">{errors.first_name.message}</p>}
          </div>

          <div className="space-y-3">
            <Label htmlFor="last_name" className="text-sm font-medium text-foreground">
              Last Name
            </Label>
            <Input
              id="last_name"
              type="text"
              placeholder="Doe"
              className="h-14 text-base focus-glow transition-all"
              autoComplete="family-name"
              {...register("last_name")}
              aria-invalid={errors.last_name ? "true" : "false"}
            />
            {errors.last_name && <p className="text-sm text-destructive mt-1">{errors.last_name.message}</p>}
          </div>
        </div>

        <div className="space-y-3">
          <Label htmlFor="address_1" className="text-sm font-medium text-foreground">
            Street Address
          </Label>
          <Input
            id="address_1"
            type="text"
            placeholder="123 Main Street"
            className="h-14 text-base focus-glow transition-all"
            autoComplete="address-line1"
            {...register("address_1")}
            aria-invalid={errors.address_1 ? "true" : "false"}
          />
          {errors.address_1 && <p className="text-sm text-destructive mt-1">{errors.address_1.message}</p>}
        </div>

        <div className="space-y-3">
          <Label htmlFor="address_2" className="text-sm font-medium text-foreground">
            Apartment, suite, etc. <span className="text-muted-foreground font-normal">(optional)</span>
          </Label>
          <Input
            id="address_2"
            type="text"
            placeholder="Apt 4B"
            className="h-14 text-base focus-glow transition-all"
            autoComplete="address-line2"
            {...register("address_2")}
          />
        </div>

        <div className="grid gap-6 sm:grid-cols-2">
          <div className="space-y-3">
            <Label htmlFor="city" className="text-sm font-medium text-foreground">
              City
            </Label>
            <Input
              id="city"
              type="text"
              placeholder="San Francisco"
              className="h-14 text-base focus-glow transition-all"
              autoComplete="address-level2"
              {...register("city")}
              aria-invalid={errors.city ? "true" : "false"}
            />
            {errors.city && <p className="text-sm text-destructive mt-1">{errors.city.message}</p>}
          </div>

          <div className="space-y-3">
            <Label htmlFor="state" className="text-sm font-medium text-foreground">
              State
            </Label>
            <Controller
              name="state"
              control={control}
              render={({ field }) => (
                <Select value={field.value} onValueChange={field.onChange}>
                  <SelectTrigger className="h-14 text-base focus-glow transition-all" id="state">
                    <SelectValue placeholder="Select state" />
                  </SelectTrigger>
                  <SelectContent className="max-h-[300px]">
                    {US_STATES.map((state) => (
                      <SelectItem key={state.value} value={state.value}>
                        {state.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              )}
            />
            {errors.state && <p className="text-sm text-destructive mt-1">{errors.state.message}</p>}
          </div>
        </div>

        <div className="grid gap-6 sm:grid-cols-2">
          <div className="space-y-3">
            <Label htmlFor="postcode" className="text-sm font-medium text-foreground">
              Postal Code
            </Label>
            <Input
              id="postcode"
              type="text"
              placeholder="94103"
              className="h-14 text-base focus-glow transition-all"
              autoComplete="postal-code"
              {...register("postcode")}
              aria-invalid={errors.postcode ? "true" : "false"}
            />
            {errors.postcode && <p className="text-sm text-destructive mt-1">{errors.postcode.message}</p>}
          </div>

          <div className="space-y-3">
            <Label htmlFor="country" className="text-sm font-medium text-foreground">
              Country
            </Label>
            <Input
              id="country"
              type="text"
              value="United States"
              className="h-14 text-base bg-muted/50 cursor-not-allowed"
              disabled
              readOnly
            />
            <input type="hidden" {...register("country")} value="US" />
          </div>
        </div>
      </div>
    </Card>
  )
}
