"use client"

import { useState, useCallback } from "react"
import { CheckoutHeader } from "@/components/checkout-header"
import { ContactInformation } from "@/components/contact-information"
import { BillingAddress } from "@/components/billing-address"
import { ShippingAddress } from "@/components/shipping-address"
import { OrderSummary } from "@/components/order-summary"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { useCheckoutData } from "@/hooks/use-checkout-data"
import { ArrowRight, Loader2, Send } from "lucide-react"
import { toast } from "sonner"
import type {
  ContactInformation as ContactInfoType,
  BillingAddress as BillingAddressType,
  ShippingAddress as ShippingAddressType,
} from "@/lib/types/checkout"

export default function CheckoutPage() {
  const [shippingSameAsBilling, setShippingSameAsBilling] = useState(true)
  const { orderData, isLoading, error, token } = useCheckoutData()

  // Form state
  const [contactInfo, setContactInfo] = useState<ContactInfoType | null>(null)
  const [billingAddress, setBillingAddress] = useState<BillingAddressType | null>(null)
  const [shippingAddress, setShippingAddress] = useState<ShippingAddressType | null>(null)
  const [isSubmitting, setIsSubmitting] = useState(false)

  const canSubmit =
    contactInfo &&
    billingAddress &&
    (shippingSameAsBilling || shippingAddress) &&
    !isSubmitting

  const handleSubmitOrder = useCallback(async () => {
    if (!token || !billingAddress || !contactInfo) return

    try {
      setIsSubmitting(true)
      console.log("[v0] Submitting order for manual payment")

      const response = await fetch("/api/submit-order", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          token,
          billing_address: billingAddress,
          shipping_address: shippingSameAsBilling ? null : shippingAddress,
          contact_info: contactInfo,
        }),
      })

      const data = await response.json()

      if (!response.ok || !data.success) {
        throw new Error(data.error?.message || "Failed to submit order")
      }

      console.log("[v0] Order submitted successfully:", data.order_id)

      // Redirect to success page with payment instructions
      window.location.href = `/success?token=${token}`
    } catch (err) {
      console.error("[v0] Failed to submit order:", err)
      toast.error(err instanceof Error ? err.message : "Failed to submit order")
    } finally {
      setIsSubmitting(false)
    }
  }, [token, billingAddress, shippingAddress, shippingSameAsBilling, contactInfo])

  if (error) {
    return (
      <div className="min-h-screen bg-texture flex items-center justify-center">
        <div className="max-w-md mx-auto p-6 text-center">
          <div className="inline-flex h-16 w-16 items-center justify-center rounded-full bg-destructive/10 mb-4">
            <svg
              className="h-8 w-8 text-destructive"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
              />
            </svg>
          </div>
          <h1 className="text-2xl font-bold text-foreground mb-2">Unable to Load Checkout</h1>
          <p className="text-muted-foreground">{error}</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-texture">
      <CheckoutHeader />

      <div className="mx-auto max-w-[1400px] px-6 pt-16 pb-12 lg:px-12">
        <div className="max-w-3xl">
          <h1 className="text-5xl font-bold tracking-tight text-foreground lg:text-6xl">
            Complete Your Order
          </h1>
          <p className="mt-6 text-xl text-muted-foreground leading-relaxed">
            Fill in your details below, then submit your order. Payment instructions will be
            provided after submission.
          </p>
        </div>
      </div>

      <div className="mx-auto max-w-[1400px] px-6 pb-24 lg:px-12">
        <div className="flex flex-col gap-8 lg:flex-row lg:gap-12">
          {/* Left Zone - Form Modules (60% width) */}
          <div className="flex-1 lg:max-w-[60%] space-y-8">
            {/* Identity Block */}
            <ContactInformation
              onChange={setContactInfo}
              defaultValues={orderData ? { email: orderData.email } : undefined}
              orderId={orderData?.id}
            />

            {/* Address Modules */}
            <div className="space-y-8">
              <BillingAddress onChange={setBillingAddress} />
              <ShippingAddress
                shippingSameAsBilling={shippingSameAsBilling}
                setShippingSameAsBilling={setShippingSameAsBilling}
                onChange={setShippingAddress}
              />
            </div>

            {/* Payment Method & Submit */}
            <div className="pt-8">
              <Card className="p-10 shadow-elevated border-primary/20 bg-gradient-to-br from-card to-card/50">
                <div className="mb-6">
                  <h2 className="text-2xl font-bold text-foreground tracking-tight mb-2">
                    Payment Method
                  </h2>
                  <p className="text-sm text-muted-foreground">
                    After submitting your order, you will receive instructions to pay via Zelle or
                    CashApp. Your order will be processed once payment is verified.
                  </p>
                </div>

                <div className="space-y-4 mb-8">
                  <div className="flex items-center gap-3 p-4 rounded-lg bg-muted/50 border border-border">
                    <div className="h-10 w-10 rounded-lg bg-primary/15 flex items-center justify-center font-bold text-primary text-sm">
                      Z
                    </div>
                    <div>
                      <p className="text-sm font-medium text-foreground">Zelle</p>
                      <p className="text-xs text-muted-foreground">
                        Send to: factorsciencesfp@gmail.com
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center gap-3 p-4 rounded-lg bg-muted/50 border border-border">
                    <div className="h-10 w-10 rounded-lg bg-green-500/15 flex items-center justify-center font-bold text-green-600 text-sm">
                      $
                    </div>
                    <div>
                      <p className="text-sm font-medium text-foreground">CashApp (Alternative)</p>
                      <p className="text-xs text-muted-foreground">$FSnorthvaleGroup</p>
                    </div>
                  </div>
                </div>

                <Button
                  size="lg"
                  className="w-full h-16 text-lg font-medium shadow-elevated hover:shadow-float transition-all duration-300 group"
                  onClick={handleSubmitOrder}
                  disabled={!canSubmit}
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 className="mr-3 h-5 w-5 animate-spin" />
                      Submitting Order...
                    </>
                  ) : (
                    <>
                      <Send className="mr-3 h-5 w-5" />
                      Submit Order
                      <ArrowRight className="ml-3 h-5 w-5 group-hover:translate-x-1 transition-transform" />
                    </>
                  )}
                </Button>

                {!canSubmit && !isSubmitting && (
                  <p className="mt-4 text-center text-sm text-muted-foreground">
                    Please complete all required fields above
                  </p>
                )}
              </Card>
            </div>
          </div>

          {/* Right Zone - Order Instrument Panel (40% width) */}
          <div className="lg:sticky lg:top-24 lg:self-start lg:max-w-[40%] flex-shrink-0 w-full">
            <OrderSummary orderData={orderData} isLoading={isLoading} error={error} />
          </div>
        </div>
      </div>
    </div>
  )
}
