"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 { Checkbox } from "@/components/ui/checkbox"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Card } from "@/components/ui/card"
import { Truck } from "lucide-react"
import { ShippingAddressSchema, type ShippingAddress as ShippingAddressType } from "@/lib/types/checkout"
import { US_STATES } from "@/lib/us-states"
import { useEffect } from "react"

interface ShippingAddressProps {
  shippingSameAsBilling: boolean
  setShippingSameAsBilling: (value: boolean) => void
  onChange?: (data: ShippingAddressType | null) => void
  defaultValues?: Partial<ShippingAddressType>
}

export function ShippingAddress({
  shippingSameAsBilling,
  setShippingSameAsBilling,
  onChange,
  defaultValues,
}: ShippingAddressProps) {
  const {
    register,
    control,
    formState: { errors },
    watch,
  } = useForm<ShippingAddressType>({
    resolver: zodResolver(ShippingAddressSchema),
    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(shippingSameAsBilling ? null : (value as ShippingAddressType))
    })
    return () => subscription.unsubscribe()
  }, [watch, onChange, shippingSameAsBilling])
  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">
            <Truck className="h-5 w-5 text-primary" />
          </div>
          <h2 className="text-2xl font-bold text-foreground tracking-tight">Shipping Address</h2>
        </div>
        <p className="text-sm text-muted-foreground">Where we'll deliver your order</p>
      </div>

      <div className="mb-8 flex items-start gap-3 p-4 rounded-lg bg-muted/30 border border-border/50">
        <Checkbox
          id="same-as-billing"
          checked={shippingSameAsBilling}
          onCheckedChange={(checked) => setShippingSameAsBilling(checked === true)}
          className="mt-0.5"
        />
        <Label htmlFor="same-as-billing" className="text-sm font-normal text-foreground cursor-pointer leading-relaxed">
          Use billing address for shipping
        </Label>
      </div>

      {!shippingSameAsBilling && (
        <div className="space-y-6 animate-in fade-in slide-in-from-top-4 duration-500">
          <div className="grid gap-6 sm:grid-cols-2">
            <div className="space-y-3">
              <Label htmlFor="shipping_first_name" className="text-sm font-medium text-foreground">
                First Name
              </Label>
              <Input
                id="shipping_first_name"
                type="text"
                placeholder="John"
                className="h-14 text-base focus-glow transition-all"
                autoComplete="shipping 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="shipping_last_name" className="text-sm font-medium text-foreground">
                Last Name
              </Label>
              <Input
                id="shipping_last_name"
                type="text"
                placeholder="Doe"
                className="h-14 text-base focus-glow transition-all"
                autoComplete="shipping 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="shipping_address_1" className="text-sm font-medium text-foreground">
              Street Address
            </Label>
            <Input
              id="shipping_address_1"
              type="text"
              placeholder="123 Main Street"
              className="h-14 text-base focus-glow transition-all"
              autoComplete="shipping 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="shipping_address_2" className="text-sm font-medium text-foreground">
              Apartment, suite, etc. <span className="text-muted-foreground font-normal">(optional)</span>
            </Label>
            <Input
              id="shipping_address_2"
              type="text"
              placeholder="Apt 4B"
              className="h-14 text-base focus-glow transition-all"
              autoComplete="shipping address-line2"
              {...register("address_2")}
            />
          </div>

          <div className="grid gap-6 sm:grid-cols-2">
            <div className="space-y-3">
              <Label htmlFor="shipping_city" className="text-sm font-medium text-foreground">
                City
              </Label>
              <Input
                id="shipping_city"
                type="text"
                placeholder="San Francisco"
                className="h-14 text-base focus-glow transition-all"
                autoComplete="shipping 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="shipping_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="shipping_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="shipping_postcode" className="text-sm font-medium text-foreground">
                Postal Code
              </Label>
              <Input
                id="shipping_postcode"
                type="text"
                placeholder="94103"
                className="h-14 text-base focus-glow transition-all"
                autoComplete="shipping 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="shipping_country" className="text-sm font-medium text-foreground">
                Country
              </Label>
              <Input
                id="shipping_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>
  )
}
