'use client'

import { useEffect, useState } from 'react'
import { formatCurrency, PLAN_PRICES } from '@rentaldrivego/types'
import { apiFetch } from '@/lib/api'

type Plan = 'STARTER' | 'GROWTH' | 'PRO'
type BillingPeriod = 'MONTHLY' | 'ANNUAL'
type Currency = 'MAD' | 'USD' | 'EUR'

interface Subscription {
  id: string
  plan: Plan
  billingPeriod: BillingPeriod
  status: string
  currency: Currency
  trialEndAt: string | null
  currentPeriodEnd: string | null
  cancelAtPeriodEnd: boolean
}

interface Invoice {
  id: string
  amount: number
  currency: Currency
  status: string
  paymentProvider: string
  paidAt: string | null
  createdAt: string
}

const STATUS_BADGE: Record<string, string> = {
  TRIALING: 'bg-sky-100 text-sky-700',
  ACTIVE: 'bg-green-100 text-green-700',
  PAST_DUE: 'bg-amber-100 text-amber-700',
  CANCELLED: 'bg-slate-100 text-slate-600',
  UNPAID: 'bg-red-100 text-red-700',
}

const INVOICE_STATUS: Record<string, string> = {
  PAID: 'bg-green-100 text-green-700',
  PENDING: 'bg-amber-100 text-amber-700',
  FAILED: 'bg-red-100 text-red-700',
  REFUNDED: 'bg-slate-100 text-slate-600',
}

const PLANS: Plan[] = ['STARTER', 'GROWTH', 'PRO']
const PLAN_FEATURES: Record<Plan, string[]> = {
  STARTER: ['Up to 10 vehicles', '1 user seat', 'Basic analytics', 'Marketplace listing'],
  GROWTH: ['Up to 50 vehicles', '5 user seats', 'Full analytics', 'Priority listing', 'Custom branding'],
  PRO: ['Unlimited vehicles', 'Unlimited seats', 'Advanced reports', 'API access', 'Dedicated support'],
}

export default function BillingPage() {
  const [subscription, setSubscription] = useState<Subscription | null>(null)
  const [invoices, setInvoices] = useState<Invoice[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const [selectedPlan, setSelectedPlan] = useState<Plan>('STARTER')
  const [billingPeriod, setBillingPeriod] = useState<BillingPeriod>('MONTHLY')
  const [currency, setCurrency] = useState<Currency>('MAD')
  const [provider, setProvider] = useState<'AMANPAY' | 'PAYPAL'>('AMANPAY')
  const [paying, setPaying] = useState(false)
  const [cancelling, setCancelling] = useState(false)

  useEffect(() => {
    Promise.all([
      apiFetch<Subscription | null>('/subscriptions/me'),
      apiFetch<Invoice[]>('/subscriptions/invoices'),
    ])
      .then(([sub, inv]) => {
        if (sub) {
          setSubscription(sub)
          setSelectedPlan(sub.plan)
          setBillingPeriod(sub.billingPeriod)
          setCurrency(sub.currency as Currency)
        }
        setInvoices(inv ?? [])
      })
      .catch((err) => setError(err.message))
      .finally(() => setLoading(false))
  }, [])

  async function handleCheckout() {
    setPaying(true)
    setError(null)
    try {
      const base = window.location.origin
      const result = await apiFetch<{ checkoutUrl: string }>('/subscriptions/checkout', {
        method: 'POST',
        body: JSON.stringify({
          plan: selectedPlan,
          billingPeriod,
          currency,
          provider,
          successUrl: `${base}/dashboard/billing?payment=success`,
          failureUrl: `${base}/dashboard/billing?payment=failed`,
        }),
      })
      window.location.href = result.checkoutUrl
    } catch (err: any) {
      setError(err.message)
      setPaying(false)
    }
  }

  async function handleCancel() {
    setCancelling(true)
    setError(null)
    try {
      const sub = await apiFetch<Subscription>('/subscriptions/cancel', { method: 'POST' })
      setSubscription(sub)
    } catch (err: any) {
      setError(err.message)
    } finally {
      setCancelling(false)
    }
  }

  async function handleResume() {
    setCancelling(true)
    setError(null)
    try {
      const sub = await apiFetch<Subscription>('/subscriptions/resume', { method: 'POST' })
      setSubscription(sub)
    } catch (err: any) {
      setError(err.message)
    } finally {
      setCancelling(false)
    }
  }

  const planPrice = PLAN_PRICES[selectedPlan]?.[billingPeriod]?.[currency]
  const daysLeft = subscription?.trialEndAt
    ? Math.ceil((new Date(subscription.trialEndAt).getTime() - Date.now()) / 86400000)
    : null

  return (
    <div className="space-y-8">
      <div>
        <h2 className="text-xl font-semibold text-slate-900">Billing</h2>
        <p className="text-sm text-slate-500 mt-1">Manage your plan, payment provider, and invoice history.</p>
      </div>

      {error && (
        <div className="card p-4 border-red-200 bg-red-50 text-sm text-red-700">{error}</div>
      )}

      {/* Trial banner */}
      {subscription?.status === 'TRIALING' && daysLeft !== null && daysLeft > 0 && (
        <div className="card p-4 border-sky-200 bg-sky-50 flex items-center justify-between">
          <p className="text-sm font-medium text-sky-800">
            Free trial — <strong>{daysLeft} days</strong> remaining. Subscribe before it ends to keep access.
          </p>
        </div>
      )}

      {/* Current plan */}
      {subscription && (
        <div className="card p-6">
          <div className="flex items-start justify-between gap-4">
            <div>
              <p className="text-xs font-medium text-slate-500 uppercase tracking-wide">Current plan</p>
              <div className="mt-1 flex items-center gap-3">
                <h3 className="text-2xl font-bold text-slate-900">{subscription.plan}</h3>
                <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${STATUS_BADGE[subscription.status] ?? 'bg-slate-100 text-slate-600'}`}>
                  {subscription.status}
                </span>
              </div>
              <p className="mt-1 text-sm text-slate-500">
                {subscription.billingPeriod} · {subscription.currency}
                {subscription.currentPeriodEnd && ` · renews ${new Date(subscription.currentPeriodEnd).toLocaleDateString()}`}
              </p>
              {subscription.cancelAtPeriodEnd && (
                <p className="mt-2 text-sm font-medium text-amber-700">
                  Cancellation scheduled at end of billing period.{' '}
                  <button onClick={handleResume} disabled={cancelling} className="underline">Undo</button>
                </p>
              )}
            </div>
            {!subscription.cancelAtPeriodEnd && (
              <button
                onClick={handleCancel}
                disabled={cancelling}
                className="btn-secondary text-red-600 border-red-200 hover:bg-red-50 text-sm"
              >
                {cancelling ? 'Cancelling…' : 'Cancel plan'}
              </button>
            )}
          </div>
        </div>
      )}

      {/* Plan selector + checkout */}
      <div className="card p-6 space-y-6">
        <div>
          <h3 className="text-base font-semibold text-slate-900">
            {subscription?.status === 'ACTIVE' ? 'Change plan' : 'Subscribe'}
          </h3>
          <p className="mt-1 text-sm text-slate-500">Select a plan and payment provider to proceed.</p>
        </div>

        {/* Billing period toggle */}
        <div className="flex items-center gap-2">
          {(['MONTHLY', 'ANNUAL'] as BillingPeriod[]).map((p) => (
            <button
              key={p}
              onClick={() => setBillingPeriod(p)}
              className={`px-4 py-1.5 rounded-full text-sm font-medium transition-colors ${
                billingPeriod === p ? 'bg-slate-900 text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'
              }`}
            >
              {p === 'MONTHLY' ? 'Monthly' : 'Annual (save ~17%)'}
            </button>
          ))}
        </div>

        {/* Currency selector */}
        <div className="flex items-center gap-2">
          {(['MAD', 'USD', 'EUR'] as Currency[]).map((c) => (
            <button
              key={c}
              onClick={() => setCurrency(c)}
              className={`px-3 py-1 rounded-lg text-sm font-medium border transition-colors ${
                currency === c ? 'border-blue-500 bg-blue-50 text-blue-700' : 'border-slate-200 text-slate-600 hover:border-slate-300'
              }`}
            >
              {c}
            </button>
          ))}
        </div>

        {/* Plan cards */}
        <div className="grid gap-4 md:grid-cols-3">
          {PLANS.map((plan) => {
            const price = PLAN_PRICES[plan]?.[billingPeriod]?.[currency]
            const isActive = subscription?.plan === plan && subscription?.status === 'ACTIVE'
            return (
              <button
                key={plan}
                onClick={() => setSelectedPlan(plan)}
                className={`text-left p-5 rounded-xl border-2 transition-all ${
                  selectedPlan === plan
                    ? 'border-blue-500 bg-blue-50/50'
                    : 'border-slate-200 hover:border-slate-300 bg-white'
                } ${isActive ? 'ring-2 ring-green-200' : ''}`}
              >
                <div className="flex items-center justify-between">
                  <p className="font-semibold text-slate-900">{plan}</p>
                  {isActive && <span className="badge-green">Active</span>}
                </div>
                <p className="mt-2 text-2xl font-black text-slate-900">
                  {price ? formatCurrency(price, currency) : '—'}
                  <span className="text-sm font-normal text-slate-500">/{billingPeriod === 'MONTHLY' ? 'mo' : 'yr'}</span>
                </p>
                <ul className="mt-3 space-y-1">
                  {PLAN_FEATURES[plan].map((f) => (
                    <li key={f} className="text-xs text-slate-600 flex items-center gap-1.5">
                      <span className="text-green-500">✓</span> {f}
                    </li>
                  ))}
                </ul>
              </button>
            )
          })}
        </div>

        {/* Provider selector */}
        <div>
          <p className="text-sm font-medium text-slate-700 mb-2">Payment provider</p>
          <div className="flex gap-3">
            {(['AMANPAY', 'PAYPAL'] as const).map((p) => (
              <button
                key={p}
                onClick={() => setProvider(p)}
                className={`flex items-center gap-2 px-4 py-2.5 rounded-xl border-2 text-sm font-medium transition-all ${
                  provider === p ? 'border-blue-500 bg-blue-50 text-blue-700' : 'border-slate-200 text-slate-600 hover:border-slate-300'
                }`}
              >
                {p === 'AMANPAY' ? '🏦 AmanPay' : '🔵 PayPal'}
              </button>
            ))}
          </div>
        </div>

        {/* Checkout CTA */}
        <div className="flex items-center justify-between pt-2 border-t border-slate-100">
          <div>
            <p className="text-sm text-slate-500">Total</p>
            <p className="text-xl font-black text-slate-900">
              {planPrice ? formatCurrency(planPrice, currency) : '—'}
              <span className="text-sm font-normal text-slate-500 ml-1">/{billingPeriod === 'MONTHLY' ? 'month' : 'year'}</span>
            </p>
          </div>
          <button
            onClick={handleCheckout}
            disabled={paying || loading}
            className="btn-primary px-8 py-3"
          >
            {paying ? 'Redirecting…' : subscription?.status === 'ACTIVE' ? 'Change plan' : 'Subscribe now'}
          </button>
        </div>
      </div>

      {/* Invoice history */}
      <div className="card overflow-hidden">
        <div className="px-6 py-4 border-b border-slate-200">
          <h3 className="text-base font-semibold text-slate-900">Invoice history</h3>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-slate-50 border-b border-slate-200">
                <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Date</th>
                <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Provider</th>
                <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Status</th>
                <th className="text-left px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Paid</th>
                <th className="text-right px-6 py-3 text-xs font-medium text-slate-500 uppercase tracking-wide">Amount</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {loading ? (
                <tr><td colSpan={5} className="px-6 py-10 text-center text-sm text-slate-400">Loading…</td></tr>
              ) : invoices.length === 0 ? (
                <tr><td colSpan={5} className="px-6 py-10 text-center text-sm text-slate-400">No invoices yet.</td></tr>
              ) : invoices.map((inv) => (
                <tr key={inv.id}>
                  <td className="px-6 py-4 text-sm text-slate-700">{new Date(inv.createdAt).toLocaleDateString()}</td>
                  <td className="px-6 py-4 text-sm text-slate-700">{inv.paymentProvider}</td>
                  <td className="px-6 py-4">
                    <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${INVOICE_STATUS[inv.status] ?? 'bg-slate-100 text-slate-600'}`}>
                      {inv.status}
                    </span>
                  </td>
                  <td className="px-6 py-4 text-sm text-slate-500">
                    {inv.paidAt ? new Date(inv.paidAt).toLocaleDateString() : '—'}
                  </td>
                  <td className="px-6 py-4 text-right text-sm font-semibold text-slate-900">
                    {formatCurrency(inv.amount, inv.currency)}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}
