'use client'

import { useMemo, useState } from 'react'
import { toast } from 'sonner'
import { useRoutingProducts, type CartItem, type RouteCart, type RouteCredits, type RouteType } from '@/components/app/route-purchase'
import { isRouteProductCode, routeTypeForProduct } from '@/lib/domain/routing-products'

/**
 * LOOK ONLY (Nash, 2026-10-01: "Add the look only"). The Pilot Dispatch trip
 * view is still a design preview on made-up assignments, so there is no real
 * trip, permit or payment behind it. This gives it the same purchase control,
 * cart bar and cart pop-up as Carrier Dispatch and Freight Broker — the real
 * components — with a cart that lives in memory and buys nothing. Prices are
 * the real catalog prices. When Pilot Dispatch gets a real trip view, this
 * file is deleted and the page sets `routePurchasing` like the other roles.
 */

/** Which product a preview permit is offered as. A permit uploaded later stands for a new route. */
export function previewRouteType(permitNumber: string): RouteType {
  return /uploaded/i.test(permitNumber) ? 'extended' : 'express'
}

export interface PreviewRoutePurchasing {
  cart: RouteCart
  credits: RouteCredits
  /** Permits whose route was taken in this preview session. */
  taken: Set<string>
  spendCredit: (permitId: string) => Promise<string | null>
  completePurchase: () => void
}

export function usePreviewRoutePurchasing(permits: Array<{ id: string; state: string }>): PreviewRoutePurchasing {
  const { products } = useRoutingProducts()
  const [lines, setLines] = useState<Array<{ permitId: string; productCode: string }>>([])
  const [taken, setTaken] = useState<Set<string>>(new Set())
  const [used, setUsed] = useState(0)
  const [reviewOpen, setReviewOpen] = useState(false)

  const items: CartItem[] = useMemo(() => lines.flatMap((l) => {
    const product = products.find((p) => p.product_code === l.productCode)
    const permit = permits.find((p) => p.id === l.permitId)
    if (!product || !permit) return []
    return [{
      id: `preview-${l.permitId}`, permitId: l.permitId, stateCode: permit.state, productCode: product.product_code,
      productName: product.product_name, routeType: isRouteProductCode(product.product_code) ? routeTypeForProduct(product.product_code) : 'express',
      unitPriceCents: product.unit_price_cents, lineTotalCents: product.unit_price_cents, warning: null,
    }]
  }), [lines, products, permits])
  const total = items.reduce((sum, i) => sum + i.lineTotalCents, 0)

  const cart: RouteCart = {
    items,
    loading: false,
    has: (permitId) => lines.some((l) => l.permitId === permitId),
    add: async ({ permitId, productCode }) => {
      setLines((cur) => [...cur.filter((l) => l.permitId !== permitId), { permitId, productCode }])
      return true
    },
    remove: async (permitId) => setLines((cur) => cur.filter((l) => l.permitId !== permitId)),
    clear: async () => setLines([]),
    refresh: async () => {},
    totalCents: total,
    subtotalCents: total,
    currency: 'USD',
    enabled: true,
    reviewOpen,
    openReview: () => setReviewOpen(true),
    closeReview: () => setReviewOpen(false),
  }

  const included = 1
  return {
    cart,
    credits: { planName: 'Preview', included, used, remaining: Math.max(included - used, 0) },
    taken,
    spendCredit: async (permitId) => {
      setUsed((n) => n + 1)
      setTaken((cur) => new Set(cur).add(permitId))
      return null
    },
    completePurchase: () => {
      const n = lines.length
      setTaken((cur) => { const next = new Set(cur); for (const l of lines) next.add(l.permitId); return next })
      setLines([])
      toast.success(`Design preview — ${n} route${n === 1 ? '' : 's'} shown as purchased. Nothing was charged.`)
    },
  }
}
