import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Building2, CreditCard } from 'lucide-react'
import { useToast } from '@meshkee/dashboard-ui'
import { useCheckout } from '../../context/CheckoutContext'
import { ApiError, isAbortError } from '../../lib/api'
import {
  checkoutCart,
  getCart,
  type CheckoutPaymentType,
  type OnlineGatewayType,
} from '../../services/cartService'
import { syncGuestCartToServer } from '../../services/syncGuestCart'
import { formatIrtPrice } from '../../utils/irtPrice'
import { CheckoutActionBar } from '../../components/checkout/CheckoutActionBar'
import { CheckoutBackButton } from '../../components/checkout/CheckoutBackButton'
import styles from './CheckoutSteps.module.css'

const ONLINE_GATEWAYS: { id: OnlineGatewayType; label: string }[] = [
  { id: 'mellat_behpardakht', label: 'درگاه پرداخت بانک ملت - به‌پرداخت' },
  { id: 'saman_kish', label: 'درگاه پرداخت بانک سامان - سامان کیش' },
]

export function CheckoutPaymentStep() {
  const navigate = useNavigate()
  const { showToast } = useToast()
  const { deliveryMode, selectedAddressId, discountCode, setDiscountCode, setPlacedOrder } =
    useCheckout()
  const [subtotal, setSubtotal] = useState(0)
  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [error, setError] = useState('')
  const [paymentType, setPaymentType] = useState<CheckoutPaymentType>('e_payment_gate')
  const [gatewayType, setGatewayType] = useState<OnlineGatewayType>('mellat_behpardakht')
  const [transferAccount, setTransferAccount] = useState('')
  const [transferRefNumber, setTransferRefNumber] = useState('')
  const [discountApplied, setDiscountApplied] = useState(false)

  useEffect(() => {
    const controller = new AbortController()

    async function load() {
      setLoading(true)
      try {
        let data = await getCart(controller.signal)
        if (controller.signal.aborted) return

        if (data.cart.items.length === 0) {
          try {
            const synced = await syncGuestCartToServer(controller.signal)
            if (controller.signal.aborted) return
            data = { cart: synced }
          } catch {
            // fall through to empty-cart redirect
          }
        }

        setSubtotal(data.cart.subtotal)
        if (data.cart.items.length === 0) {
          navigate('/checkout/cart', { replace: true })
        }
      } catch (err) {
        if (isAbortError(err)) return
        setError(err instanceof ApiError ? err.message : 'بارگذاری سبد خرید ممکن نشد.')
      } finally {
        if (!controller.signal.aborted) setLoading(false)
      }
    }

    void load()
    return () => controller.abort()
  }, [navigate])

  function handleApplyDiscount() {
    if (!discountCode.trim()) return
    setDiscountApplied(true)
    showToast('کد تخفیف هنوز فعال نیست — مبلغ تغییری نکرد.', 'info')
  }

  function buildPaymentPayload() {
    if (paymentType === 'transfer') {
      return {
        type: 'transfer' as const,
        transferAccount: transferAccount.trim(),
        transferRefNumber: transferRefNumber.trim(),
      }
    }

    return {
      type: 'e_payment_gate' as const,
      gatewayType,
    }
  }

  async function handlePlaceOrder() {
    setError('')

    if (deliveryMode === 'delivery' && !selectedAddressId) {
      setError('لطفاً یک آدرس ارسال انتخاب کنید.')
      return
    }

    // Only bank transfer requires extra fields before creating the order
    if (paymentType === 'transfer') {
      if (!transferAccount.trim() || !transferRefNumber.trim()) {
        setError('لطفاً شماره حساب/کارت و شماره مرجع را وارد کنید.')
        return
      }
    }

    setSubmitting(true)

    const notes: string[] = []
    if (deliveryMode === 'pickup') {
      notes.push('تحویل حضوری از فروشگاه')
    }
    if (discountCode.trim()) {
      notes.push(`کد تخفیف: ${discountCode.trim()}`)
    }

    try {
      // Both types persist via existing backend TransactionType:
      // e_payment_gate (+ gatewayType) | transfer (+ account/ref)
      const payment = buildPaymentPayload()
      const payload =
        deliveryMode === 'pickup'
          ? {
              shippingAddress: {
                province: 'Pickup',
                city: 'Store',
                address: 'In-store pickup',
                postalCode: '0000000000',
              },
              customerNotes: notes.join(' · ') || undefined,
              payment,
            }
          : {
              addressId: selectedAddressId!,
              customerNotes: notes.join(' · ') || undefined,
              payment,
            }

      const result = await checkoutCart(payload)
      setPlacedOrder(result.order)
      // Pass order in navigation state so success page does not race context updates
      navigate('/checkout/success', { replace: true, state: { order: result.order } })
      showToast('سفارش با موفقیت ثبت شد.', 'success')
    } catch (err) {
      const message = err instanceof ApiError ? err.message : 'ثبت سفارش ممکن نشد.'
      navigate('/checkout/failed', { replace: true, state: { message } })
    } finally {
      setSubmitting(false)
    }
  }

  if (loading) {
    return <div className={styles.loading}>در حال بارگذاری...</div>
  }

  return (
    <div className={styles.stepContent}>
      <CheckoutBackButton
        label="بازگشت به ارسال"
        onClick={() => navigate('/checkout/delivery')}
      />

      <div>
        <h1 className={styles.stepTitle}>پرداخت</h1>
        <p className={styles.stepDesc}>کد تخفیف را وارد کنید و روش پرداخت را انتخاب کنید.</p>
      </div>

      {error && (
        <div className={styles.error} role="alert">
          {error}
        </div>
      )}

      <div className={styles.field}>
        <label htmlFor="discount-code">کد تخفیف</label>
        <div className={styles.discountRow}>
          <input
            id="discount-code"
            type="text"
            placeholder="کد را وارد کنید"
            value={discountCode}
            onChange={(e) => {
              setDiscountCode(e.target.value)
              setDiscountApplied(false)
            }}
            disabled={submitting}
          />
          <button
            type="button"
            className={styles.applyBtn}
            onClick={handleApplyDiscount}
            disabled={submitting || !discountCode.trim()}
          >
            اعمال
          </button>
        </div>
        {discountApplied && (
          <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>
            کد ذخیره شد — در یادداشت سفارش ثبت می‌شود.
          </span>
        )}
      </div>

      <div className={styles.field}>
        <label>روش پرداخت</label>
        <div className={styles.paymentOptions}>
          <button
            type="button"
            className={[
              styles.paymentOption,
              paymentType === 'e_payment_gate' ? styles.paymentOptionActive : '',
            ]
              .filter(Boolean)
              .join(' ')}
            onClick={() => setPaymentType('e_payment_gate')}
            disabled={submitting}
          >
            <CreditCard size={20} />
            <span className={styles.paymentOptionBody}>
              <span className={styles.paymentOptionTitle}>پرداخت آنلاین</span>
              <span className={styles.paymentOptionHint}>پرداخت امن از طریق درگاه</span>
            </span>
          </button>

          {paymentType === 'e_payment_gate' && (
            <div className={styles.paymentSubOptions} role="radiogroup" aria-label="انتخاب درگاه">
              {ONLINE_GATEWAYS.map((gateway) => {
                const active = gatewayType === gateway.id
                return (
                  <button
                    key={gateway.id}
                    type="button"
                    role="radio"
                    aria-checked={active}
                    className={[
                      styles.paymentSubOption,
                      active ? styles.paymentSubOptionActive : '',
                    ]
                      .filter(Boolean)
                      .join(' ')}
                    onClick={() => setGatewayType(gateway.id)}
                    disabled={submitting}
                  >
                    <span className={styles.paymentSubRadio}>
                      {active ? <span className={styles.paymentSubRadioInner} /> : null}
                    </span>
                    <span>{gateway.label}</span>
                  </button>
                )
              })}
            </div>
          )}

          <button
            type="button"
            className={[
              styles.paymentOption,
              paymentType === 'transfer' ? styles.paymentOptionActive : '',
            ]
              .filter(Boolean)
              .join(' ')}
            onClick={() => setPaymentType('transfer')}
            disabled={submitting}
          >
            <Building2 size={20} />
            <span className={styles.paymentOptionBody}>
              <span className={styles.paymentOptionTitle}>جابجایی بانکی</span>
              <span className={styles.paymentOptionHint}>واریز به حساب و ثبت شماره مرجع</span>
            </span>
          </button>

          {paymentType === 'transfer' && (
            <div className={styles.transferFields}>
              <div className={styles.field}>
                <label htmlFor="transfer-account">شماره حساب بانکی یا کارت شما</label>
                <input
                  id="transfer-account"
                  type="text"
                  inputMode="numeric"
                  value={transferAccount}
                  onChange={(e) => setTransferAccount(e.target.value)}
                  placeholder="شماره حساب یا کارت"
                  disabled={submitting}
                  dir="ltr"
                />
              </div>
              <div className={styles.field}>
                <label htmlFor="transfer-ref">شماره مرجع</label>
                <input
                  id="transfer-ref"
                  type="text"
                  value={transferRefNumber}
                  onChange={(e) => setTransferRefNumber(e.target.value)}
                  placeholder="شماره مرجع تراکنش"
                  disabled={submitting}
                  dir="ltr"
                />
              </div>
            </div>
          )}
        </div>
      </div>

      <div className={styles.summary}>
        <div className={styles.summaryRow}>
          <span>جمع جزء</span>
          <span className={styles.priceEn}>{formatIrtPrice(subtotal)}</span>
        </div>
        <div className={styles.summaryRow}>
          <span>تخفیف</span>
          <span className={styles.priceEn}>۰ IRT</span>
        </div>
        <div className={`${styles.summaryRow} ${styles.summaryRowTotal}`}>
          <span>مبلغ قابل پرداخت</span>
          <span className={styles.priceEn}>{formatIrtPrice(subtotal)}</span>
        </div>
      </div>

      <CheckoutActionBar
        primaryLabel={submitting ? 'در حال ثبت سفارش...' : 'پرداخت و ثبت سفارش'}
        onPrimary={() => void handlePlaceOrder()}
        primaryDisabled={submitting}
      />
    </div>
  )
}
