"use client"

import { useState, useCallback, useMemo } from "react"
import { Elements } from "@stripe/react-stripe-js"
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 { PaymentSection } from "@/components/payment-section"
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 { useStripePayment } from "@/hooks/use-stripe-payment"
import { getStripe, getStripeAppearance } from "@/lib/stripe-client"
import { ArrowRight, Lock, Loader2 } from "lucide-react"
import { toast } from "sonner"
import { useTheme } from "next-themes"
import type { ContactInformation as ContactInfoType, BillingAddress as BillingAddressType, ShippingAddress as ShippingAddressType } from "@/lib/types/checkout"

// Separate component that uses Stripe hooks - must be inside Elements provider
function CheckoutFormWithStripe({ 
  token, 
  billingAddress, 
  shippingAddress, 
  shippingSameAsBilling,
  clientSecret,
  onClientSecretChange 
}: { 
  token: string
  billingAddress: BillingAddressType | null
  shippingAddress: ShippingAddressType | null
  shippingSameAsBilling: boolean
  clientSecret?: string
  onClientSecretChange: (secret: string) => void
}) {
  const [isCreatingIntent, setIsCreatingIntent] = useState(false)
  const [isPaymentElementReady, setIsPaymentElementReady] = useState(false)

  // Payment processing - NOW INSIDE Elements provider
  const { processPayment, isProcessing } = useStripePayment({
    token,
    onSuccess: (paymentIntentId) => {
      // Client-side logging - keep console.log for browser debugging
      console.log("[v0] Payment succeeded:", paymentIntentId)
    },
    onError: (error) => {
      toast.error(error.message)
    },
  })

  // Create payment intent and update addresses
  const handleCreatePaymentIntent = useCallback(async () => {
    if (!token) {
      toast.error("Missing checkout token")
      return
    }

    if (!billingAddress) {
      toast.error("Please fill in your billing address")
      return
    }

    try {
      setIsCreatingIntent(true)

      console.log("[v0] Creating payment intent with addresses")

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

      const data = await response.json()

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

      console.log("[v0] Payment intent created successfully:", data.payment_intent_id)
      
      onClientSecretChange(data.client_secret)
      // Reset payment element ready state when new client secret is set
      setIsPaymentElementReady(false)
      toast.success("Payment ready - enter your card details below")
    } catch (err) {
      console.error("[v0] Failed to create payment intent:", err)
      toast.error(err instanceof Error ? err.message : "Failed to prepare payment")
    } finally {
      setIsCreatingIntent(false)
    }
  }, [token, billingAddress, shippingAddress, shippingSameAsBilling, onClientSecretChange])
  
  // Handle payment element ready
  const handlePaymentElementReady = useCallback(() => {
    console.log("[v0] Payment Element is ready")
    setIsPaymentElementReady(true)
  }, [])

  // Submit payment
  const handleSubmit = async () => {
    if (!billingAddress) {
      toast.error("Please fill in your billing address")
      return
    }

    if (!shippingSameAsBilling && !shippingAddress) {
      toast.error("Please fill in your shipping address")
      return
    }

    if (!clientSecret) {
      // Create payment intent first
      await handleCreatePaymentIntent()
      return
    }

    // Check if payment element is ready
    if (!isPaymentElementReady) {
      toast.error("Payment form is still loading. Please wait a moment.")
      console.warn("[v0] Payment Element not ready yet")
      return
    }

    // Process payment
    await processPayment(billingAddress, shippingSameAsBilling ? null : shippingAddress)
  }

  const isFormDisabled = isProcessing || isCreatingIntent
  const canSubmit = billingAddress && (shippingSameAsBilling || shippingAddress) && !isFormDisabled && (!clientSecret || isPaymentElementReady)

  return (
    <>
      {/* Payment Module - Elevated importance */}
      <div className="pt-8">
        <PaymentSection clientSecret={clientSecret} onReady={handlePaymentElementReady} />
      </div>

      {/* Primary CTA - Large and confident */}
      <div className="pt-12">
        <Button
          size="lg"
          className="w-full h-16 text-lg font-medium shadow-elevated hover:shadow-float transition-all duration-300 group"
          onClick={handleSubmit}
          disabled={!canSubmit}
        >
          {isProcessing || isCreatingIntent ? (
            <>
              <Loader2 className="mr-3 h-5 w-5 animate-spin" />
              {isCreatingIntent ? "Preparing Payment..." : "Processing Payment..."}
            </>
          ) : clientSecret && !isPaymentElementReady ? (
            <>
              <Loader2 className="mr-3 h-5 w-5 animate-spin" />
              Loading Payment Form...
            </>
          ) : (
            <>
              <Lock className="mr-3 h-5 w-5" />
              {clientSecret ? "Complete Secure Purchase" : "Continue to Payment"}
              <ArrowRight className="ml-3 h-5 w-5 group-hover:translate-x-1 transition-transform" />
            </>
          )}
        </Button>
        <p className="mt-4 text-center text-sm text-muted-foreground">
          Protected by 256-bit SSL encryption
        </p>
      </div>
    </>
  )
}

export default function CheckoutPage() {
  const { theme } = useTheme()
  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 [clientSecret, setClientSecret] = useState<string | undefined>(undefined)
  const [isCreatingIntent, setIsCreatingIntent] = useState(false)

  // Memoize the callback to prevent infinite re-renders
  const handleClientSecretChange = useCallback((secret: string) => {
    setClientSecret(secret)
  }, [])

  // Memoize appearance to prevent Elements from re-mounting
  const appearance = useMemo(() => getStripeAppearance(theme === "dark" ? "dark" : "light"), [theme])

  // Removed auto-create payment intent - now triggered by user clicking "Continue to Payment"

  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">
            Secure checkout powered by advanced encryption. Your information is protected.
          </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 form wrapped in Elements provider */}
            {token && clientSecret && (
              <Elements 
                stripe={getStripe()} 
                options={{ 
                  clientSecret,
                  appearance 
                }} 
                key={clientSecret}
              >
                <CheckoutFormWithStripe
                  token={token}
                  billingAddress={billingAddress}
                  shippingAddress={shippingAddress}
                  shippingSameAsBilling={shippingSameAsBilling}
                  clientSecret={clientSecret}
                  onClientSecretChange={handleClientSecretChange}
                />
              </Elements>
            )}
            
            {/* Show "Continue to Payment" button when addresses are complete */}
            {token && !clientSecret && (
              <div className="space-y-8 pt-8">
                <Card className="p-10 shadow-elevated border-border/50 bg-card/80 backdrop-blur-sm">
                  <div className="text-center py-8">
                    <div className="mb-6">
                      <Lock className="h-12 w-12 mx-auto text-muted-foreground/50" />
                    </div>
                    <h3 className="text-xl font-semibold text-foreground mb-2">Ready to checkout?</h3>
                    <p className="text-sm text-muted-foreground mb-8">
                      {!contactInfo || !billingAddress || (!shippingSameAsBilling && !shippingAddress)
                        ? "Please complete all required fields above"
                        : "Click below to proceed to payment"}
                    </p>
                    <Button
                      size="lg"
                      className="h-14 px-8 text-base font-medium"
                      onClick={async () => {
                        if (!token || !billingAddress) return
                        
                        try {
                          setIsCreatingIntent(true)
                          
                          const response = await fetch("/api/payment-intent", {
                            method: "POST",
                            headers: { "Content-Type": "application/json" },
                            body: JSON.stringify({
                              token,
                              billing_address: billingAddress,
                              shipping_address: shippingSameAsBilling ? null : shippingAddress,
                            }),
                          })

                          const data = await response.json()

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

                          setClientSecret(data.client_secret)
                          toast.success("Payment ready - enter your card details below")
                          
                          // Scroll to payment section
                          setTimeout(() => {
                            document.getElementById('payment-element')?.scrollIntoView({ 
                              behavior: 'smooth', 
                              block: 'center' 
                            })
                          }, 100)
                        } catch (err) {
                          console.error("[v0] Failed to create payment intent:", err)
                          toast.error(err instanceof Error ? err.message : "Failed to prepare payment")
                        } finally {
                          setIsCreatingIntent(false)
                        }
                      }}
                      disabled={!contactInfo || !billingAddress || (!shippingSameAsBilling && !shippingAddress) || isCreatingIntent}
                    >
                      {isCreatingIntent ? (
                        <>
                          <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                          Preparing Payment...
                        </>
                      ) : (
                        <>
                          Continue to Payment
                          <ArrowRight className="ml-2 h-5 w-5" />
                        </>
                      )}
                    </Button>
                  </div>
                </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>
  )
}
