/**
 * Success Page
 * Displays order confirmation and manual payment instructions after order submission
 */

"use client"

import { Suspense, useState, useEffect } from "react"
import { useSearchParams } from "next/navigation"
import { CheckoutHeader } from "@/components/checkout-header"
import { Card } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import {
  CheckCircle2,
  Copy,
  ExternalLink,
  Mail,
  Clock,
  AlertCircle,
} from "lucide-react"
import { Separator } from "@/components/ui/separator"
import { toast } from "sonner"

function SuccessContent() {
  const searchParams = useSearchParams()
  const token = searchParams.get("token")

  const [orderData, setOrderData] = useState<{
    id: number
    total: number
    currency: string
    email: string
  } | null>(null)
  const [isLoading, setIsLoading] = useState(true)

  // Fetch order data
  useEffect(() => {
    if (!token) return

    const fetchOrder = async () => {
      try {
        const response = await fetch(`/api/checkout-session?token=${token}`)
        const data = await response.json()
        if (data.success && data.order) {
          setOrderData({
            id: data.order.id,
            total: data.order.total_cents,
            currency: data.order.currency || "USD",
            email: data.order.email || "",
          })
        }
      } catch (err) {
        console.error("[v0] Failed to fetch order data:", err)
      } finally {
        setIsLoading(false)
      }
    }

    fetchOrder()
  }, [token])

  const copyToClipboard = (text: string, label: string) => {
    navigator.clipboard.writeText(text).then(() => {
      toast.success(`${label} copied to clipboard`)
    })
  }

  if (!token) {
    return (
      <div className="min-h-screen bg-texture flex items-center justify-center">
        <Card className="p-10 max-w-md 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">Invalid Request</h1>
          <p className="text-muted-foreground">
            Missing order information. Please contact support.
          </p>
        </Card>
      </div>
    )
  }

  const totalFormatted = orderData
    ? `$${(orderData.total / 100).toFixed(2)}`
    : "..."

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

      <div className="mx-auto max-w-3xl px-6 py-16 lg:py-24">
        <div className="max-w-2xl mx-auto space-y-8">
          {/* Success Header */}
          <div className="text-center">
            <div className="inline-flex h-20 w-20 items-center justify-center rounded-full bg-gradient-to-br from-green-400 to-green-600 mb-6 shadow-xl shadow-green-500/30 animate-in zoom-in duration-500">
              <CheckCircle2 className="h-11 w-11 text-white" strokeWidth={2.5} />
            </div>
            <h1 className="text-4xl md:text-5xl font-bold text-foreground mb-3 animate-in fade-in slide-in-from-bottom-4 duration-700">
              Order Submitted!
            </h1>
            <p className="text-lg text-muted-foreground animate-in fade-in slide-in-from-bottom-4 duration-700 delay-100">
              Your order has been received. Please complete payment using the instructions below.
            </p>
          </div>

          {/* Order Info */}
          {orderData && (
            <Card className="p-8 text-center animate-in fade-in slide-in-from-bottom-4 duration-700 delay-150">
              <p className="text-sm text-muted-foreground">Order Number</p>
              <p className="text-3xl font-bold text-foreground mt-1">#{orderData.id}</p>
              <Separator className="my-4" />
              <p className="text-sm text-muted-foreground">Amount Due</p>
              <p className="text-4xl font-bold text-foreground mt-1 tabular-nums">
                {totalFormatted}
              </p>
              <p className="text-xs text-muted-foreground mt-1">{orderData.currency}</p>
            </Card>
          )}

          {isLoading && (
            <Card className="p-8 text-center">
              <div className="h-8 w-8 border-2 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4" />
              <p className="text-muted-foreground">Loading order details...</p>
            </Card>
          )}

          {/* Zelle Payment Instructions */}
          <Card className="p-8 border-primary/20 shadow-elevated animate-in fade-in slide-in-from-bottom-4 duration-700 delay-200">
            <div className="flex items-center gap-3 mb-6">
              <div className="h-12 w-12 rounded-xl bg-primary/15 flex items-center justify-center font-bold text-primary text-lg">
                Z
              </div>
              <div>
                <h2 className="text-2xl font-bold text-foreground">Pay with Zelle</h2>
                <p className="text-sm text-muted-foreground">Preferred payment method</p>
              </div>
            </div>

            <div className="space-y-4">
              <div className="flex items-center justify-between p-4 rounded-lg bg-muted/50 border border-border">
                <div>
                  <p className="text-xs text-muted-foreground mb-1">Send Zelle payment to:</p>
                  <p className="text-base font-semibold text-foreground">
                    factorsciencesfp@gmail.com
                  </p>
                </div>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() =>
                    copyToClipboard("factorsciencesfp@gmail.com", "Zelle email")
                  }
                >
                  <Copy className="h-4 w-4" />
                </Button>
              </div>

              <div className="p-4 rounded-lg bg-primary/5 border border-primary/20">
                <p className="text-sm font-semibold text-foreground mb-3">
                  Payment Requirements:
                </p>
                <ul className="space-y-2 text-sm text-muted-foreground">
                  <li className="flex items-start gap-2">
                    <span className="text-primary font-bold mt-0.5">1.</span>
                    <span>
                      Send the exact amount:{" "}
                      <strong className="text-foreground">{totalFormatted}</strong>
                    </span>
                  </li>
                  <li className="flex items-start gap-2">
                    <span className="text-primary font-bold mt-0.5">2.</span>
                    <span>Include your full name in the memo/note</span>
                  </li>
                  <li className="flex items-start gap-2">
                    <span className="text-primary font-bold mt-0.5">3.</span>
                    <span>
                      Include your order number:{" "}
                      <strong className="text-foreground">
                        #{orderData?.id || "..."}
                      </strong>
                    </span>
                  </li>
                </ul>
              </div>
            </div>
          </Card>

          {/* CashApp Alternative */}
          <Card className="p-8 animate-in fade-in slide-in-from-bottom-4 duration-700 delay-250">
            <div className="flex items-center gap-3 mb-6">
              <div className="h-12 w-12 rounded-xl bg-green-500/15 flex items-center justify-center font-bold text-green-600 text-lg">
                $
              </div>
              <div>
                <h2 className="text-2xl font-bold text-foreground">
                  CashApp (Alternative Option)
                </h2>
                <p className="text-sm text-muted-foreground">
                  Use CashApp if Zelle is not available
                </p>
              </div>
            </div>

            <div className="flex items-center justify-between p-4 rounded-lg bg-muted/50 border border-border mb-4">
              <div>
                <p className="text-xs text-muted-foreground mb-1">CashApp:</p>
                <p className="text-base font-semibold text-foreground">$FSnorthvaleGroup</p>
              </div>
              <Button variant="outline" size="sm" asChild>
                <a
                  href="https://cash.app/$FSnorthvaleGroup"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="gap-2"
                >
                  Open CashApp
                  <ExternalLink className="h-4 w-4" />
                </a>
              </Button>
            </div>

            <p className="text-sm text-muted-foreground">
              Same requirements apply: send the exact amount ({totalFormatted}), include your
              full name and order number (#{orderData?.id || "..."}).
            </p>
          </Card>

          {/* Send Screenshot */}
          <Card className="p-8 border-accent/20 animate-in fade-in slide-in-from-bottom-4 duration-700 delay-300">
            <div className="flex items-center gap-3 mb-4">
              <div className="h-12 w-12 rounded-xl bg-accent/15 flex items-center justify-center">
                <Mail className="h-6 w-6 text-accent-foreground" />
              </div>
              <div>
                <h2 className="text-xl font-bold text-foreground">Send Payment Screenshot</h2>
                <p className="text-sm text-muted-foreground">Required for verification</p>
              </div>
            </div>

            <div className="p-4 rounded-lg bg-muted/50 border border-border mb-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs text-muted-foreground mb-1">
                    Email your screenshot to:
                  </p>
                  <p className="text-base font-semibold text-foreground">
                    support@factorsciences.com
                  </p>
                </div>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() =>
                    copyToClipboard("support@factorsciences.com", "Support email")
                  }
                >
                  <Copy className="h-4 w-4" />
                </Button>
              </div>
            </div>

            <p className="text-sm text-muted-foreground">
              Include your order number <strong className="text-foreground">#{orderData?.id || "..."}</strong> in
              the email subject line. Attach a screenshot or confirmation of your Zelle/CashApp
              payment.
            </p>
          </Card>

          {/* What Happens Next */}
          <Card className="p-8 animate-in fade-in slide-in-from-bottom-4 duration-700 delay-350">
            <div className="flex items-center gap-3 mb-6">
              <div className="h-12 w-12 rounded-xl bg-primary/15 flex items-center justify-center">
                <Clock className="h-6 w-6 text-primary" />
              </div>
              <h2 className="text-xl font-bold text-foreground">What Happens Next?</h2>
            </div>

            <ul className="space-y-4">
              <li className="flex items-start gap-3">
                <div className="h-6 w-6 rounded-full bg-yellow-500/15 flex items-center justify-center flex-shrink-0 mt-0.5">
                  <AlertCircle className="h-3.5 w-3.5 text-yellow-600" />
                </div>
                <div>
                  <p className="text-sm font-medium text-foreground">
                    Order Status: Pending Payment Verification
                  </p>
                  <p className="text-sm text-muted-foreground">
                    Your order will not be processed until payment is verified
                  </p>
                </div>
              </li>
              <li className="flex items-start gap-3">
                <CheckCircle2 className="h-6 w-6 text-muted-foreground/50 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="text-sm font-medium text-foreground">Payment Verification</p>
                  <p className="text-sm text-muted-foreground">
                    Our team will verify your payment within 1-2 business days
                  </p>
                </div>
              </li>
              <li className="flex items-start gap-3">
                <CheckCircle2 className="h-6 w-6 text-muted-foreground/50 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="text-sm font-medium text-foreground">Email Confirmation</p>
                  <p className="text-sm text-muted-foreground">
                    You will receive an email at{" "}
                    <strong className="text-foreground">
                      {orderData?.email || "your email"}
                    </strong>{" "}
                    once your payment is approved
                  </p>
                </div>
              </li>
              <li className="flex items-start gap-3">
                <CheckCircle2 className="h-6 w-6 text-muted-foreground/50 flex-shrink-0 mt-0.5" />
                <div>
                  <p className="text-sm font-medium text-foreground">Order Fulfillment</p>
                  <p className="text-sm text-muted-foreground">
                    Your order will be fulfilled after payment approval
                  </p>
                </div>
              </li>
            </ul>
          </Card>

          {/* Support Contact */}
          <div className="text-center text-sm text-muted-foreground pt-4">
            <p>
              Questions? Contact us at{" "}
              <a
                href="mailto:support@factorsciences.com"
                className="text-primary hover:underline"
              >
                support@factorsciences.com
              </a>{" "}
              or call{" "}
              <a href="tel:+18182536096" className="text-primary hover:underline">
                +1 (818) 253-6096
              </a>
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}

export default function SuccessPage() {
  return (
    <Suspense
      fallback={
        <div className="min-h-screen bg-texture flex items-center justify-center">
          <div className="text-center">
            <div className="h-8 w-8 border-2 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4" />
            <p className="text-muted-foreground">Loading...</p>
          </div>
        </div>
      }
    >
      <SuccessContent />
    </Suspense>
  )
}
