'use client'

import { useState } from 'react'
import { toast } from 'sonner'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { BUSINESS_TOOLS, CORE_TOOLS, CURRENT_PLAN, PAYG, PLANS, PRO_UPGRADE_PITCH, type Plan } from '@/lib/demo/credits'
import type { RouteCredits } from '@/components/app/route-purchase'
import { formatDateTime } from '@/lib/format'
import { stateName } from '@/lib/domain/states'

/**
 * Billing & Wallet per the pricing strategy doc (2026-09-07): four plans
 * (Free / Starter / Pro / Pro Plus), volume-not-capability, AI Credits + Express
 * Route credits, dollar-style balances (never token math), upgrade-first
 * empty states. Payments are not connected yet — actions explain that.
 *
 * The "Preview state" switcher exists so the low-balance / out-of-credit
 * designs are reviewable without a metering backend.
 */

export interface RoutePurchaseRow {
  id: string
  state_code: string | null
  status: string
  route_type: 'express' | 'extended' | null
  requester_label: string
  created_at: string
  trip_label: string
}

type PreviewState = 'fresh' | 'low' | 'out_credits' | 'out_routes'

function previewToast() {
  toast.info('Preview only — payments are not connected yet.')
}

export function BillingPreview({
  routePurchases,
  routeCredits,
  internal = false,
}: {
  routePurchases: RoutePurchaseRow[]
  /** Real Express Route usage this cycle (Task 69) — the number the permit cards decrement. */
  routeCredits: RouteCredits
  /**
   * Internal staff see the design-state switcher (Task 96). Nash: "all the
   * design previews … should be for admin and developers only." The
   * "payments are not connected" sentence stays for everyone — that is an
   * honest disclosure, not a preview control.
   */
  internal?: boolean
}) {
  const [preview, setPreview] = useState<PreviewState>('fresh')
  const plan = CURRENT_PLAN

  // AI Credits stay a static design preview (metering is backend). Express
  // Routes are REAL: "When I buy one, it's gonna go drop to 14, to 13" — only
  // the "Out of routes" preview overrides them to show that design state.
  const usage = {
    fresh: { routesUsed: routeCredits.used, creditsRemaining: '$1.00', creditsUsed: '$0.00' },
    low: { routesUsed: routeCredits.used, creditsRemaining: '$0.50', creditsUsed: '$0.50' },
    out_credits: { routesUsed: routeCredits.used, creditsRemaining: '$0.00', creditsUsed: '$1.00' },
    out_routes: { routesUsed: plan.routes, creditsRemaining: '$1.00', creditsUsed: '$0.00' },
  }[preview]

  return (
    <div className="mx-auto max-w-5xl space-y-8">
      <div>
        <h1 className="text-2xl font-bold">Billing &amp; Wallet</h1>
        <p className="mt-1 text-sm text-neutral-500">
          Your plan, Express Route credits, AI Credits, and route purchases.
        </p>
      </div>

      <div className="rounded-xl border border-amber-300 bg-amber-50 p-4 text-sm text-amber-900">
        <span className="font-semibold">Preview.</span> Payments are not connected in this pilot
        build — no charge occurs. Balances below show the design with sample usage.
        {internal && (
        <span className="ml-3 inline-flex items-center gap-1 text-xs">
          Preview state:
          {(
            [
              ['fresh', 'Fresh'],
              ['low', 'Low balance'],
              ['out_credits', 'Out of AI Credits'],
              ['out_routes', 'Out of routes'],
            ] as const
          ).map(([key, label]) => (
            <button
              key={key}
              onClick={() => setPreview(key)}
              className={`rounded-full px-2 py-0.5 font-semibold ${
                preview === key ? 'bg-amber-900 text-white' : 'bg-white/70 hover:bg-white'
              }`}
            >
              {label}
            </button>
          ))}
        </span>
        )}
      </div>

      {/* Wallet: current plan + usage, dollar-style balances (never tokens) */}
      <div className="grid gap-4 sm:grid-cols-2">
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center justify-between text-base">
              Your plan
              <Badge>{plan.name}</Badge>
            </CardTitle>
            <CardDescription>
              ${plan.price}/month · {plan.routes} Express Route{plan.routes === 1 ? '' : 's'} ·
              ${plan.credits} AI Credits included monthly
            </CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <p className="text-xs font-bold uppercase tracking-wide text-neutral-400">
                Express Routes
              </p>
              <p className="mt-0.5 text-sm">
                {plan.routes} included · {usage.routesUsed} used ·{' '}
                <span className={`font-bold ${plan.routes - usage.routesUsed === 0 ? 'text-amber-700' : ''}`}>
                  {plan.routes - usage.routesUsed} remaining
                </span>
              </p>
            </div>
            <div>
              <p className="text-xs font-bold uppercase tracking-wide text-neutral-400">
                AI Credits
              </p>
              <p className="mt-0.5 text-sm">
                ${plan.credits.toFixed(2)} included · {usage.creditsUsed} used ·{' '}
                <span className={`font-bold ${preview === 'low' || preview === 'out_credits' ? 'text-amber-700' : ''}`}>
                  {usage.creditsRemaining} remaining
                </span>
              </p>
            </div>
            <p className="text-xs text-neutral-500">
              Bonus AI Credits from route purchases: $0.00 — every route purchase includes bonus AI
              Credits to help you ask questions about your permit, restrictions, curfews, and
              escorts.
            </p>
            <Button size="sm" onClick={previewToast}>Upgrade plan</Button>
          </CardContent>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle className="text-base">Payment method</CardTitle>
            <CardDescription>Card on file for routes and subscriptions</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="rounded-lg border border-dashed p-4 text-center text-sm text-neutral-500">
              No card on file
            </div>
            <AddCardDialog />
          </CardContent>
        </Card>
      </div>

      {/* Low-balance / out-of-credit designs (upgrade-first, per the doc) */}
      {preview === 'low' && (
        <div className="rounded-xl border border-amber-300 bg-amber-50 p-4 text-sm text-amber-900">
          <p className="font-semibold">You are almost out of AI Credits.</p>
          <p className="mt-1">
            You have $0.50 in AI Credits remaining this month. Upgrade now to continue asking
            questions without interruption.
          </p>
          <Button size="sm" className="mt-3" onClick={previewToast}>Upgrade plan</Button>
        </div>
      )}
      {preview === 'out_credits' && (
        <div className="rounded-xl border border-amber-300 bg-amber-50 p-4">
          <p className="text-sm font-semibold text-amber-900">
            You have used your included AI Credits for this month. Upgrade your plan to continue
            asking permit questions and receive more Express Route credits every month.
          </p>
          <div className="mt-3 grid gap-3 sm:grid-cols-3">
            {PLANS.filter((p) => p.price > 0).map((p, i) => (
              <button
                key={p.name}
                onClick={previewToast}
                className={`rounded-xl border bg-white p-3 text-left text-sm transition hover:border-neutral-400 ${
                  i === 0 ? 'border-[#f5a623] ring-1 ring-[#f5a623]/50' : ''
                }`}
              >
                <p className="font-bold">
                  Upgrade to {p.name}
                  {i === 0 && <span className="ml-1.5 text-[10px] font-bold text-[#d98b06]">RECOMMENDED</span>}
                </p>
                <p className="mt-0.5 text-xs text-neutral-500">
                  ${p.price}/month, {p.routes} Express Routes, ${p.credits} AI Credits
                </p>
              </button>
            ))}
          </div>
          <p className="mt-2 text-xs text-amber-800/70">
            Already on Pro Plus? We&apos;ll review your usage and set up a custom volume plan —
            contact us.
          </p>
        </div>
      )}
      {preview === 'out_routes' && (
        <div className="rounded-xl border border-amber-300 bg-amber-50 p-4 text-sm text-amber-900">
          <p className="font-semibold">
            You have used all included Express Route credits for this month. Upgrade your plan for
            more monthly Express Routes, or purchase this route individually.
          </p>
          <div className="mt-3 flex flex-wrap gap-2">
            <Button size="sm" onClick={previewToast}>Upgrade plan</Button>
            <Button size="sm" variant="outline" onClick={previewToast}>
              Buy Express Route for {PAYG.express.price}
            </Button>
          </div>
          <p className="mt-2 text-xs">
            A pay-as-you-go Express Route includes: 1 Express Route · {PAYG.express.bonus} bonus AI
            Credits · route saved to the trip · visible to everyone connected to the trip.
          </p>
        </div>
      )}

      {/* Plans — "Choose your HeavyHaul Agent plan" (copy per the strategy doc) */}
      <section>
        <h2 className="text-xl font-bold">Choose your HeavyHaul Agent plan</h2>
        {/* Positioning per the Pro Tools article (2026-09-12, §4 / §7): core
            operational tools on every plan; business tools on Pro and Pro Plus. */}
        <p className="mt-1 max-w-3xl text-sm text-neutral-600">
          Core operational tools are on every plan — permit uploads, shared permit viewing, AI
          permit questions, trip workspaces, pilot assignment access, invites, profile and history.
          Plans differ in included Express Routes, AI Credits, business tools, and monthly
          usage.
        </p>
        <p className="mt-2 max-w-3xl text-xs text-neutral-500">
          Each paid dollar includes one monthly Express Route credit. AI Credits are included for
          permit questions, provision questions, curfew checks, escort checks, and trip
          intelligence.
        </p>
        <div className="mt-4 grid gap-3 rounded-lg bg-neutral-50 p-3 text-xs text-neutral-600 sm:grid-cols-2">
          <div>
            <p className="font-semibold text-neutral-800">Core operational tools — every plan</p>
            <p className="mt-1">{CORE_TOOLS.join(' · ')}</p>
          </div>
          <div>
            <p className="font-semibold text-neutral-800">Business management tools — Pro and Pro Plus</p>
            <p className="mt-1">{BUSINESS_TOOLS.join(' · ')}</p>
            <p className="mt-1.5 font-medium text-[#d98b06]">{PRO_UPGRADE_PITCH}</p>
          </div>
        </div>
        <div className="mt-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
          {PLANS.map((p) => (
            <PlanCard key={p.name} plan={p} current={p.name === CURRENT_PLAN.name} />
          ))}
        </div>
        <div className="mt-4 grid gap-3 text-xs text-neutral-500 sm:grid-cols-2">
          <p>
            <span className="font-semibold text-neutral-700">Express Routes</span> are fast Google
            Maps route requests for familiar or simple permitted routes.
          </p>
          <p>
            <span className="font-semibold text-neutral-700">Extended Routes</span> are more
            complex route requests and are billed separately when required.
          </p>
        </div>
      </section>

      {/* Pay-as-you-go route products */}
      <section>
        <h2 className="mb-1 text-lg font-bold">Pay-as-you-go routes</h2>
        <p className="mb-3 text-xs text-neutral-500">
          Monthly plans include Express Route credits. Extended Routes are billed separately when
          required.
        </p>
        <div className="grid gap-4 sm:grid-cols-2">
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Express Route — {PAYG.express.price}</CardTitle>
              <CardDescription>
                A known state-to-state route we&apos;ve done before — delivered very fast as an
                easy-to-follow visual Google Map. Includes {PAYG.express.bonus} bonus AI Credits.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Button size="sm" onClick={previewToast}>Buy Express Route</Button>
            </CardContent>
          </Card>
          <Card>
            <CardHeader>
              <CardTitle className="text-base">Extended Route — {PAYG.extended.price}</CardTitle>
              <CardDescription>
                A new or complex route — our team takes more time to execute and deliver it.
                Includes {PAYG.extended.bonus} bonus AI Credits. Included Express Route credits
                cannot be used for Extended Routes.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <Button size="sm" onClick={previewToast}>Request Extended Route</Button>
            </CardContent>
          </Card>
        </div>
        <p className="mt-2 text-xs text-neutral-500">
          Every route purchase includes bonus AI Credits to help you ask questions about your
          permit, restrictions, curfews, and escorts. One purchase unlocks the route for everyone
          on that trip — participants never pay twice for the same route.
        </p>
      </section>

      {/* Route purchase history — real data from the user's trips */}
      <section>
        <h2 className="mb-3 text-lg font-bold">Route purchase history</h2>
        {routePurchases.length === 0 ? (
          <div className="rounded-xl border border-dashed p-8 text-center text-sm text-neutral-500">
            No route purchases yet. Buy a route from any permit on your trips.
          </div>
        ) : (
          <div className="space-y-2">
            {routePurchases.map((r) => (
              <div key={r.id} className="flex items-center justify-between rounded-xl border bg-white p-3 text-sm">
                <div className="min-w-0">
                  <p className="font-semibold">
                    {r.state_code ? stateName(r.state_code) : 'Route'}
                    {r.route_type && (
                      <span className="ml-1.5 text-xs font-normal capitalize text-neutral-500">
                        {r.route_type} · {r.route_type === 'express' ? PAYG.express.price : PAYG.extended.price}
                      </span>
                    )}
                  </p>
                  <p className="truncate text-xs text-neutral-500">
                    {r.trip_label} · by {r.requester_label} · {formatDateTime(r.created_at)}
                  </p>
                </div>
                <Badge variant="outline" className="capitalize">{r.status.replace('_', ' ')}</Badge>
              </div>
            ))}
          </div>
        )}
      </section>

      {/* Invoices */}
      <section>
        <h2 className="mb-3 text-lg font-bold">Invoices</h2>
        <div className="rounded-xl border border-dashed p-8 text-center text-sm text-neutral-500">
          No invoices yet. Purchases and subscription payments will appear here once billing goes
          live.
        </div>
      </section>
    </div>
  )
}

function PlanCard({ plan, current }: { plan: Plan; current: boolean }) {
  return (
    <Card className={current ? 'border-neutral-900' : ''}>
      <CardHeader className="pb-2">
        <CardTitle className="flex items-center justify-between text-base">
          {plan.name}
          {current && <Badge>Current plan</Badge>}
        </CardTitle>
        <p className="text-2xl font-bold">
          ${plan.price} <span className="text-xs font-normal text-neutral-500">/month</span>
        </p>
      </CardHeader>
      <CardContent className="space-y-2 text-sm">
        <p className="text-xs text-neutral-600">{plan.tagline}</p>
        <p className="font-semibold">
          {plan.routes} Express Route{plan.routes === 1 ? '' : 's'} / month
        </p>
        <p className="font-semibold">${plan.credits} AI Credits / month</p>
        <ul className="space-y-0.5 text-xs text-neutral-600">
          {plan.includes.map((item) => (
            <li key={item}>✓ {item}</li>
          ))}
        </ul>
        <p className="text-xs text-neutral-500">Best for: {plan.bestFor}</p>
        {plan.positioning && (
          <p className="text-xs italic text-neutral-400">{plan.positioning}</p>
        )}
        {!current && (
          <Button size="sm" variant="outline" className="w-full" onClick={previewToast}>
            Upgrade
          </Button>
        )}
      </CardContent>
    </Card>
  )
}

/** Card-on-file dialog — full UI, submits to a preview notice until payments connect. */
function AddCardDialog() {
  const [open, setOpen] = useState(false)
  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button size="sm">Add card</Button>
      </DialogTrigger>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Add a payment card</DialogTitle>
        </DialogHeader>
        <form
          className="space-y-4"
          onSubmit={(e) => {
            e.preventDefault()
            setOpen(false)
            toast.info('Preview — card storage activates when payments are connected.')
          }}
        >
          <div className="space-y-2">
            <Label htmlFor="cc-name">Name on card</Label>
            <Input id="cc-name" placeholder="Full name" required />
          </div>
          <div className="space-y-2">
            <Label htmlFor="cc-number">Card number</Label>
            <Input id="cc-number" inputMode="numeric" placeholder="4242 4242 4242 4242" required />
          </div>
          <div className="grid grid-cols-2 gap-4">
            <div className="space-y-2">
              <Label htmlFor="cc-exp">Expiry</Label>
              <Input id="cc-exp" placeholder="MM / YY" required />
            </div>
            <div className="space-y-2">
              <Label htmlFor="cc-cvc">CVC</Label>
              <Input id="cc-cvc" inputMode="numeric" placeholder="123" required />
            </div>
          </div>
          <Button type="submit" className="w-full">Save card</Button>
          <p className="text-center text-xs text-neutral-500">
            Preview — no card data is stored or transmitted yet. Secure card storage arrives with
            the payment provider.
          </p>
        </form>
      </DialogContent>
    </Dialog>
  )
}
