import { useState, type FormEvent } from 'react'
import { PaymentElement, useStripe, useElements } from '@stripe/react-stripe-js'
import type { StripePaymentElementOptions } from '@stripe/stripe-js'

export interface StripePaymentFormProps {
  amount: number
  currency?: string
  onSuccess: (paymentIntentId: string) => void
  onError: (error: string) => void
  isProcessing?: boolean
  submitLabel?: string
}

export function StripePaymentForm({
  amount,
  currency = 'EUR',
  onSuccess,
  onError,
  isProcessing = false,
  submitLabel,
}: StripePaymentFormProps) {
  const stripe = useStripe()
  const elements = useElements()
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [errorMessage, setErrorMessage] = useState<string | null>(null)
  const [isReady, setIsReady] = useState(false)

  const loading = isProcessing || isSubmitting

  const label =
    submitLabel || `Pay ${currency.toUpperCase()} ${amount.toFixed(2)}`

  const paymentElementOptions: StripePaymentElementOptions = {
    layout: 'tabs',
  }

  async function handleSubmit(e: FormEvent) {
    e.preventDefault()

    if (!stripe || !elements) return

    setIsSubmitting(true)
    setErrorMessage(null)

    const { error, paymentIntent } = await stripe.confirmPayment({
      elements,
      redirect: 'if_required',
    })

    if (error) {
      // PaymentIntent already succeeded (webhook race) — treat as success
      if (error.payment_intent && error.payment_intent.status === 'succeeded') {
        onSuccess(error.payment_intent.id)
        setIsSubmitting(false)
        return
      }

      setErrorMessage(error.message || 'Payment failed')
      onError(error.message || 'Payment failed')
      setIsSubmitting(false)
      return
    }

    if (paymentIntent && paymentIntent.status === 'succeeded') {
      onSuccess(paymentIntent.id)
    } else if (paymentIntent) {
      setErrorMessage('Payment requires additional action')
      onError('Payment requires additional action')
    }

    setIsSubmitting(false)
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <PaymentElement
        options={paymentElementOptions}
        onReady={() => setIsReady(true)}
      />

      {errorMessage && (
        <div className="rounded-md bg-red-50 p-3 text-sm text-red-700">
          {errorMessage}
        </div>
      )}

      <button
        type="submit"
        disabled={!stripe || !elements || loading || !isReady}
        className={[
          'w-full rounded-lg px-4 py-3 text-sm font-semibold text-white transition-colors',
          'focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500',
          loading || !isReady
            ? 'cursor-not-allowed bg-gray-400'
            : 'bg-blue-600 hover:bg-blue-700',
        ].join(' ')}
      >
        {loading ? (
          <span className="flex items-center justify-center gap-2">
            <svg
              className="h-4 w-4 animate-spin"
              xmlns="http://www.w3.org/2000/svg"
              fill="none"
              viewBox="0 0 24 24"
            >
              <circle
                className="opacity-25"
                cx="12"
                cy="12"
                r="10"
                stroke="currentColor"
                strokeWidth="4"
              />
              <path
                className="opacity-75"
                fill="currentColor"
                d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
              />
            </svg>
            Processing...
          </span>
        ) : (
          label
        )}
      </button>
    </form>
  )
}
