'use client'

import { useMemo, useState } from 'react'
import { loadStripe, type Stripe as StripeJs } from '@stripe/stripe-js'
import { Elements, PaymentElement, useElements, useStripe } from '@stripe/react-stripe-js'
import { useTranslations } from 'next-intl'
import { toast } from 'react-hot-toast'
import { Loader2, Lock } from 'lucide-react'
import { getApiErrorMessage } from '@/lib/utils/apiError'
import { toStripeAmount } from '@/lib/payments/stripeCurrency'
import type { PlacedOrderResult } from '@/components/frontend/checkout/PayPalCheckoutButton'

interface StripeCheckoutFormProps {
  publishableKey: string
  currency: string
  // Shown on the form and used by Stripe to pick wallets; the amount actually
  // charged is always computed on the server.
  total: number
  totalLabel: string
  checkoutBody: Record<string, unknown>
  onPlaced: (order: PlacedOrderResult) => void
}

// loadStripe must run once per key, not on every render.
const stripePromises = new Map<string, Promise<StripeJs | null>>()
function getStripe(key: string) {
  if (!stripePromises.has(key)) stripePromises.set(key, loadStripe(key))
  return stripePromises.get(key)!
}

function cssVar(name: string, fallback: string): string {
  if (typeof window === 'undefined') return fallback
  const el = document.querySelector('[data-storefront]') ?? document.documentElement
  return getComputedStyle(el).getPropertyValue(name).trim() || fallback
}

// Card checkout with Stripe's Payment Element. Loaded (with Stripe.js) only
// when the shopper picks card payment. Flow:
//   1. Pay → Stripe validates the card form (elements.submit)
//   2. POST /api/frontend/payments/stripe/create-intent → server prices the
//      cart and creates the PaymentIntent
//   3. stripe.confirmPayment → card is charged (3-D Secure pops up here if
//      the bank asks for it; no page redirect)
//   4. POST /api/frontend/payments/stripe/finalize → order is placed
// If the browser dies after step 3, the Stripe webhook places the order.
export default function StripeCheckoutForm(props: StripeCheckoutFormProps) {
  const stripePromise = getStripe(props.publishableKey)
  const options = useMemo(
    () => ({
      mode: 'payment' as const,
      amount: toStripeAmount(props.total, props.currency),
      currency: props.currency.toLowerCase(),
      paymentMethodTypes: ['card'],
      appearance: {
        theme: 'stripe' as const,
        variables: {
          colorPrimary: cssVar('--primary', '#0f766e'),
          borderRadius: '8px',
        },
      },
    }),
    [props.total, props.currency],
  )

  return (
    <Elements stripe={stripePromise} options={options}>
      <StripePayForm {...props} />
    </Elements>
  )
}

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))

function StripePayForm({ checkoutBody, onPlaced, totalLabel }: StripeCheckoutFormProps) {
  const t = useTranslations('Checkout')
  const stripe = useStripe()
  const elements = useElements()
  const [busy, setBusy] = useState<'idle' | 'paying' | 'confirming'>('idle')
  const [error, setError] = useState<string | null>(null)
  const [ready, setReady] = useState(false)

  // The browser may arrive while the webhook is placing the same order —
  // the server answers 409 PROCESSING; ask again for a few seconds.
  const finalize = async (paymentIntentId: string, clientSecret: string) => {
    for (let attempt = 0; attempt < 6; attempt++) {
      const res = await fetch('/api/frontend/payments/stripe/finalize', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ payment_intent_id: paymentIntentId, client_secret: clientSecret }),
      })
      const data = await res.json().catch(() => ({}))
      if (res.ok && data.success) return data.data as PlacedOrderResult
      if (data.code === 'PROCESSING') {
        await sleep(1500)
        continue
      }
      throw new Error(getApiErrorMessage(data, t('stripeError')))
    }
    throw new Error(t('stripeStillConfirming'))
  }

  const handlePay = async () => {
    if (!stripe || !elements || busy !== 'idle') return
    setError(null)
    setBusy('paying')
    try {
      const { error: submitError } = await elements.submit()
      if (submitError) {
        setError(submitError.message ?? t('stripeError'))
        setBusy('idle')
        return
      }

      const res = await fetch('/api/frontend/payments/stripe/create-intent', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify(checkoutBody),
      })
      const data = await res.json().catch(() => ({}))
      if (!res.ok || !data.success) {
        setError(getApiErrorMessage(data, t('stripeError')))
        setBusy('idle')
        return
      }
      const clientSecret: string = data.data.client_secret

      const { error: confirmError, paymentIntent } = await stripe.confirmPayment({
        elements,
        clientSecret,
        confirmParams: { return_url: window.location.href },
        redirect: 'if_required',
      })
      if (confirmError) {
        // Declined card, wrong CVC, failed 3-D Secure… nothing was charged.
        setError(confirmError.message ?? t('stripeError'))
        setBusy('idle')
        return
      }
      if (!paymentIntent || (paymentIntent.status !== 'succeeded' && paymentIntent.status !== 'processing')) {
        setError(t('stripeError'))
        setBusy('idle')
        return
      }

      setBusy('confirming')
      const order = await finalize(paymentIntent.id, clientSecret)
      onPlaced(order)
    } catch (err) {
      const message = err instanceof Error ? err.message : t('networkError')
      setError(message)
      toast.error(message, { duration: 8000 })
      setBusy('idle')
    }
  }

  return (
    <div className="mt-6 space-y-4">
      <div className="rounded-xl border border-gray-200 bg-white p-4">
        <PaymentElement onReady={() => setReady(true)} options={{ layout: 'tabs' }} />
        {!ready && <div className="h-40 animate-pulse rounded-lg bg-gray-100" />}
      </div>

      {error && <p className="text-sm text-red-600" role="alert">{error}</p>}

      <button
        type="button"
        onClick={handlePay}
        disabled={!stripe || !ready || busy !== 'idle'}
        className="w-full inline-flex items-center justify-center gap-2 bg-gradient-primary text-white py-3 rounded-lg font-semibold hover:shadow-md transition disabled:opacity-50 cursor-pointer"
      >
        {busy === 'idle' ? (
          <>
            <Lock size={16} />
            {t('stripePay', { amount: totalLabel })}
          </>
        ) : (
          <>
            <Loader2 size={18} className="animate-spin" />
            {busy === 'paying' ? t('stripeProcessing') : t('paypalProcessing')}
          </>
        )}
      </button>

      <p className="flex items-center justify-center gap-1.5 text-xs text-gray-custom">
        <Lock size={12} />
        {t('stripeSecureNote')}
      </p>
    </div>
  )
}
