'use client'

import { useEffect, useState } from 'react'
import { Badge } from '@/components/ui/badge'
import { startCheckout } from '@/components/app/route-purchase'
import { FULFILLMENT_STATUS_LABELS, PURCHASE_STATUS_LABELS, isCheckoutReopenable } from '@/lib/domain/purchases'
import { formatCents } from '@/lib/domain/routing-products'
import { stateName } from '@/lib/domain/states'
import { formatDateTime } from '@/lib/format'
import type { PaymentReference, Purchase, PurchaseItem } from '@/types/db'

/**
 * "Routing purchases" under the trip overview (task §14, Task 7.2). Each
 * purchase is paid on its own; the copy must never suggest the whole Synchron
 * order is paid. Renders nothing while the trip has no route purchases.
 */

interface Bundle {
  purchase: Purchase
  items: PurchaseItem[]
  payment: PaymentReference | null
}

/** Product name from the snapshot on the item; `product_name` is not stored, so derive it from the code. */
function productLabel(item: PurchaseItem): string {
  if (item.product_code === 'express_route') return 'Express Route'
  if (item.product_code === 'extended_route') return 'Extended Route'
  return item.route_type === 'extended' ? 'Extended Route' : 'Express Route'
}

export function RoutePurchaseHistory({ tripId, permitStates = {} }: { tripId: string; permitStates?: Record<string, string | null> }) {
  const [bundles, setBundles] = useState<Bundle[]>([])
  const [busy, setBusy] = useState<string | null>(null)

  useEffect(() => {
    let alive = true
    fetch(`/api/trips/${tripId}/purchases`)
      .then(async (res) => {
        const json = await res.json().catch(() => ({}))
        if (alive && res.ok && Array.isArray(json.purchases)) setBundles(json.purchases as Bundle[])
      })
      .catch(() => {
        // history is informational — a failed load just leaves it empty
      })
    return () => {
      alive = false
    }
  }, [tripId])

  if (bundles.length === 0) return null

  async function resume(purchaseId: string) {
    setBusy(purchaseId)
    try {
      await startCheckout(purchaseId)
    } finally {
      setBusy(null)
    }
  }

  return (
    <div className="mt-4 border-t pt-3">
      <h4 className="text-xs font-bold uppercase tracking-wide text-neutral-500">Routing purchases</h4>
      <p className="mt-1 text-[11px] text-neutral-500">
        Each purchase is paid separately. A paid route purchase does not mean the whole Synchron order is paid.
      </p>
      <ul className="mt-2 space-y-3 text-sm">
        {bundles.map(({ purchase, items }) => (
          <li key={purchase.id} className="rounded-lg border p-2.5">
            <div className="flex flex-wrap items-center justify-between gap-2">
              <span className="min-w-0">
                <span className="text-[11px] text-neutral-500">{formatDateTime(purchase.created_at)}</span>
                <span className="ml-2 font-mono text-[11px] text-neutral-500">{purchase.purchase_reference}</span>
              </span>
              <span className="flex items-center gap-2">
                <Badge variant="outline">{PURCHASE_STATUS_LABELS[purchase.purchase_status] ?? purchase.purchase_status}</Badge>
                {isCheckoutReopenable(purchase.purchase_status) && (
                  <button
                    type="button"
                    onClick={() => void resume(purchase.id)}
                    disabled={busy === purchase.id}
                    className="text-[11px] font-bold text-navy-900 underline underline-offset-2 disabled:opacity-60"
                  >
                    {busy === purchase.id ? 'Opening…' : 'Continue to payment'}
                  </button>
                )}
              </span>
            </div>
            <ul className="mt-1.5 space-y-1">
              {items.map((item) => {
                const state = item.hha_permit_id ? permitStates[item.hha_permit_id] : null
                return (
                  <li key={item.id} className="flex items-center justify-between gap-2 text-xs">
                    <span className="min-w-0 truncate">
                      {state ? `${stateName(state)} ` : ''}
                      {productLabel(item)}
                      {item.quantity > 1 ? ` × ${item.quantity}` : ''}
                    </span>
                    <span className="flex shrink-0 items-center gap-2">
                      <span className="font-mono">{formatCents(item.line_total_cents, item.currency)}</span>
                      <Badge variant="outline" className="text-[10px]">
                        {FULFILLMENT_STATUS_LABELS[item.fulfillment_status] ?? item.fulfillment_status}
                      </Badge>
                    </span>
                  </li>
                )
              })}
            </ul>
            <p className="mt-1.5 flex items-center justify-between border-t pt-1.5 text-xs font-bold">
              <span>Purchase total</span>
              <span className="font-mono">{formatCents(purchase.total_amount_cents, purchase.currency)}</span>
            </p>
          </li>
        ))}
      </ul>
    </div>
  )
}
