'use client'

import { useState } from 'react'
import { PayPalScriptProvider, PayPalButtons } from '@paypal/react-paypal-js'
import { useTranslations } from 'next-intl'
import { toast } from 'react-hot-toast'
import { Loader2 } from 'lucide-react'
import { getApiErrorMessage } from '@/lib/utils/apiError'

export interface PlacedOrderResult {
  id: string
  order_number: string
  is_new_account: boolean
  account_email?: string
}

interface PayPalCheckoutButtonProps {
  clientId: string
  currency: string
  // The same checkout details the COD/bank flow posts (address, email...).
  checkoutBody: Record<string, unknown>
  onPlaced: (order: PlacedOrderResult) => void
  disabled?: boolean
}

// PayPal smart buttons for checkout. Loaded (with PayPal's SDK) only when
// the shopper picks PayPal. The server does all the money logic:
//   createOrder → POST /api/frontend/payments/paypal/create-order
//   onApprove   → POST /api/frontend/payments/paypal/capture-order
// The amount is never sent from here — the server prices the cart itself.
export default function PayPalCheckoutButton({ clientId, currency, checkoutBody, onPlaced, disabled }: PayPalCheckoutButtonProps) {
  const t = useTranslations('Checkout')
  const [processing, setProcessing] = useState(false)

  return (
    <div className="relative mt-6">
      <PayPalScriptProvider
        // Pay Later is turned off: only PayPal balance/bank and cards.
        options={{ clientId, currency, intent: 'capture', components: 'buttons', disableFunding: 'paylater' }}
      >
        <PayPalButtons
          style={{ layout: 'vertical', shape: 'rect', label: 'pay', height: 48 }}
          disabled={disabled || processing}
          // Re-render the buttons when the currency changes.
          forceReRender={[currency]}
          createOrder={async () => {
            const res = await fetch('/api/frontend/payments/paypal/create-order', {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              credentials: 'include',
              body: JSON.stringify(checkoutBody),
            })
            const data = await res.json().catch(() => ({}))
            if (!res.ok || !data.success) {
              const message = getApiErrorMessage(data, t('paypalError'))
              toast.error(message)
              throw new Error(message)
            }
            return data.data.paypal_order_id as string
          }}
          onApprove={async (data, actions) => {
            setProcessing(true)
            try {
              const res = await fetch('/api/frontend/payments/paypal/capture-order', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify({ ...checkoutBody, paypal_order_id: data.orderID }),
              })
              const result = await res.json().catch(() => ({}))
              if (result.code === 'INSTRUMENT_DECLINED') {
                // Let the buyer pick another card/funding source in the same popup.
                toast.error(getApiErrorMessage(result, t('paypalDeclined')))
                setProcessing(false)
                return actions.restart()
              }
              if (!res.ok || !result.success) {
                toast.error(getApiErrorMessage(result, t('paypalError')), { duration: 8000 })
                setProcessing(false)
                return
              }
              onPlaced(result.data as PlacedOrderResult)
            } catch {
              toast.error(t('networkError'))
              setProcessing(false)
            }
          }}
          onCancel={() => {
            toast(t('paypalCancelled'))
          }}
          onError={(err) => {
            // createOrder already showed its own message.
            console.error('[PayPal]', err)
          }}
        />
      </PayPalScriptProvider>

      {processing && (
        <div className="absolute inset-0 z-10 flex items-center justify-center gap-2 rounded-lg bg-white/85 text-sm font-medium text-dark">
          <Loader2 size={18} className="animate-spin text-primary" />
          {t('paypalProcessing')}
        </div>
      )}
    </div>
  )
}
