'use client'

import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Checkbox } from '@/components/ui/checkbox'
import { updateBillingConfig } from '@/app/actions/admin-billing'
import { toast } from 'sonner'
import { useLanguage } from '@/lib/i18n'
import {
  CreditCard,
  Gauge,
  Coins,
  Package,
  Activity,
  CheckCircle2,
  XCircle,
  AlertTriangle,
  Users,
  BookOpen,
  ChevronDown,
  ChevronUp,
} from 'lucide-react'
import { cn } from '@/lib/utils'

type PriceHealth = {
  key: string
  priceId: string
  configured: boolean
  source: string
  stripeAmount: number | null
  stripeCurrency: string | null
  stripeActive: boolean | null
  error: string | null
}

type BillingAdminData = {
  billingConfig: Record<string, string>
  usageOverview: {
    period: string
    lastSyncedAt: string | null
    byFeature: Array<{ feature: string; requests: number; tokens: number; users: number }>
    topUsers: Array<{ userId: string; email: string; name: string | null; requests: number }>
  }
  tiers: string[]
  creditAllocations?: Array<{
    tier: string
    monthlyCredits: number | null
    unlimited: boolean
  }>
  creditCosts?: Record<string, number>
  creditPacks?: Array<{
    id: string
    credits: number
    defaultDisplay: string
  }>
  stripeHealth?: {
    secretConfigured: boolean
    secretMode: 'test' | 'live' | 'missing' | 'placeholder'
    publishableConfigured: boolean
    webhookSecretConfigured: boolean
    billingEnabled: boolean
    trialDays: number
    prices: PriceHealth[]
  }
  subscriptionStats?: {
    byTier: Record<string, number>
    byStatus: Record<string, number>
    cancelAtPeriodEnd: number
    usersWithoutSub: number
    trialing: number
    pastDue: number
    paidActive: number
    recent: Array<{
      email: string
      name: string | null
      tier: string
      status: string
      trialEndsAt: string | null
      currentPeriodEnd: string | null
      cancelAtPeriodEnd: boolean
      hasStripeSub: boolean
      updatedAt: string
    }>
  }
}

const SUBSCRIPTION_PRICE_KEYS = [
  'STRIPE_PRICE_PRO_MONTHLY',
  'STRIPE_PRICE_PRO_ANNUAL',
  'STRIPE_PRICE_BUSINESS_MONTHLY',
  'STRIPE_PRICE_BUSINESS_ANNUAL',
] as const

const PACK_PRICE_KEYS = [
  'STRIPE_PRICE_CREDITS_S',
  'STRIPE_PRICE_CREDITS_M',
  'STRIPE_PRICE_CREDITS_L',
] as const

function formatStableUtc(iso: string): string {
  const d = new Date(iso)
  if (Number.isNaN(d.getTime())) return iso
  const pad = (n: number) => String(n).padStart(2, '0')
  return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())} UTC`
}

function StatusDot({ ok, warn }: { ok: boolean; warn?: boolean }) {
  if (ok) return <CheckCircle2 className="h-4 w-4 text-emerald-600 shrink-0" />
  if (warn) return <AlertTriangle className="h-4 w-4 text-amber-500 shrink-0" />
  return <XCircle className="h-4 w-4 text-rose-500 shrink-0" />
}

export function BillingAdminClient({ initialData }: { initialData: BillingAdminData }) {
  const { t } = useLanguage()
  const [billingEnabled, setBillingEnabled] = useState(initialData.billingConfig.BILLING_ENABLED === 'true')
  const [isSavingBilling, setIsSavingBilling] = useState(false)
  const [showTestGuide, setShowTestGuide] = useState(true)

  const health = initialData.stripeHealth
  const stats = initialData.subscriptionStats
  const priceMap = Object.fromEntries((health?.prices ?? []).map((p) => [p.key, p]))

  const handleSaveBilling = async (formData: FormData) => {
    setIsSavingBilling(true)
    try {
      const data: Record<string, string> = {
        BILLING_ENABLED: billingEnabled ? 'true' : 'false',
      }
      for (const key of [...SUBSCRIPTION_PRICE_KEYS, ...PACK_PRICE_KEYS]) {
        data[key] = String(formData.get(key) ?? '')
      }
      await updateBillingConfig(data)
      toast.success(t('admin.billing.configSaved'))
    } catch (e: unknown) {
      toast.error(e instanceof Error ? e.message : t('admin.billing.configFailed'))
    } finally {
      setIsSavingBilling(false)
    }
  }

  const modeLabel =
    health?.secretMode === 'test'
      ? t('admin.billing.modeTest')
      : health?.secretMode === 'live'
        ? t('admin.billing.modeLive')
        : health?.secretMode === 'placeholder'
          ? t('admin.billing.modePlaceholder')
          : t('admin.billing.modeMissing')

  return (
    <div className="space-y-8">
      <div>
        <h1 className="font-memento-serif text-2xl font-semibold">{t('admin.billing.title')}</h1>
        <p className="text-sm text-muted-foreground mt-1">{t('admin.billing.description')}</p>
      </div>

      {/* Stripe health */}
      {health && (
        <div className="bg-card rounded-lg border border-border shadow-sm overflow-hidden">
          <div className="flex items-center gap-3 p-6 border-b border-border">
            <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
              <Activity className="h-5 w-5" />
            </div>
            <div>
              <h2 className="font-semibold">{t('admin.billing.healthTitle')}</h2>
              <p className="text-sm text-muted-foreground">{t('admin.billing.healthDescription')}</p>
            </div>
          </div>
          <div className="p-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
            <div className="flex items-start gap-2 rounded-xl border border-border/60 bg-muted/20 p-3">
              <StatusDot ok={health.secretConfigured} warn={health.secretMode === 'placeholder'} />
              <div className="min-w-0">
                <p className="text-xs font-semibold">{t('admin.billing.healthSecret')}</p>
                <p className="text-[11px] text-muted-foreground">{modeLabel}</p>
              </div>
            </div>
            <div className="flex items-start gap-2 rounded-xl border border-border/60 bg-muted/20 p-3">
              <StatusDot ok={health.publishableConfigured} />
              <div>
                <p className="text-xs font-semibold">{t('admin.billing.healthPublishable')}</p>
                <p className="text-[11px] text-muted-foreground">
                  {health.publishableConfigured ? t('admin.billing.configured') : t('admin.billing.missing')}
                </p>
              </div>
            </div>
            <div className="flex items-start gap-2 rounded-xl border border-border/60 bg-muted/20 p-3">
              <StatusDot ok={health.webhookSecretConfigured} />
              <div>
                <p className="text-xs font-semibold">{t('admin.billing.healthWebhook')}</p>
                <p className="text-[11px] text-muted-foreground">
                  {health.webhookSecretConfigured ? t('admin.billing.configured') : t('admin.billing.missing')}
                </p>
              </div>
            </div>
            <div className="flex items-start gap-2 rounded-xl border border-border/60 bg-muted/20 p-3">
              <StatusDot ok={health.billingEnabled} warn={!health.billingEnabled} />
              <div>
                <p className="text-xs font-semibold">{t('admin.billing.healthBillingFlag')}</p>
                <p className="text-[11px] text-muted-foreground">
                  {health.billingEnabled ? t('admin.billing.enabled') : t('admin.billing.disabled')}
                </p>
              </div>
            </div>
            <div className="flex items-start gap-2 rounded-xl border border-border/60 bg-muted/20 p-3">
              <StatusDot ok />
              <div>
                <p className="text-xs font-semibold">{t('admin.billing.healthTrial')}</p>
                <p className="text-[11px] text-muted-foreground">
                  {t('admin.billing.trialDaysValue', { days: health.trialDays })}
                </p>
              </div>
            </div>
          </div>
          <div className="px-6 pb-6">
            <h3 className="text-sm font-medium mb-3">{t('admin.billing.priceStatusTitle')}</h3>
            <div className="overflow-x-auto rounded-xl border border-border/60">
              <table className="w-full text-xs">
                <thead className="bg-muted/40 text-muted-foreground">
                  <tr>
                    <th className="text-start p-2.5 font-medium">{t('admin.billing.colKey')}</th>
                    <th className="text-start p-2.5 font-medium">{t('admin.billing.colPriceId')}</th>
                    <th className="text-start p-2.5 font-medium">{t('admin.billing.colSource')}</th>
                    <th className="text-start p-2.5 font-medium">{t('admin.billing.colStripe')}</th>
                  </tr>
                </thead>
                <tbody>
                  {(health.prices ?? []).map((row) => (
                    <tr key={row.key} className="border-t border-border/50">
                      <td className="p-2.5 font-mono">{t(`admin.billing.${row.key}`)}</td>
                      <td className="p-2.5 font-mono truncate max-w-[180px]">
                        {row.configured ? row.priceId : '—'}
                      </td>
                      <td className="p-2.5">{row.source}</td>
                      <td className="p-2.5">
                        {!row.configured ? (
                          <span className="text-rose-600">{t('admin.billing.missing')}</span>
                        ) : row.error ? (
                          <span className="text-rose-600" title={row.error}>{t('admin.billing.priceError')}</span>
                        ) : row.stripeAmount != null ? (
                          <span className={cn(row.stripeActive === false && 'text-amber-600')}>
                            {row.stripeAmount.toLocaleString('fr-FR', { minimumFractionDigits: 2 })} {row.stripeCurrency}
                            {row.stripeActive === false ? ` (${t('admin.billing.inactive')})` : ''}
                          </span>
                        ) : (
                          <span className="text-muted-foreground">{t('admin.billing.notChecked')}</span>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      )}

      {/* Subscription stats */}
      {stats && (
        <div className="bg-card rounded-lg border border-border shadow-sm overflow-hidden">
          <div className="flex items-center gap-3 p-6 border-b border-border">
            <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
              <Users className="h-5 w-5" />
            </div>
            <div>
              <h2 className="font-semibold">{t('admin.billing.subsTitle')}</h2>
              <p className="text-sm text-muted-foreground">{t('admin.billing.subsDescription')}</p>
            </div>
          </div>
          <div className="p-6 grid grid-cols-2 sm:grid-cols-4 gap-3">
            <div className="rounded-xl border border-border/60 bg-muted/20 p-4">
              <p className="text-[10px] uppercase tracking-widest text-muted-foreground font-bold">{t('admin.billing.statPaid')}</p>
              <p className="text-2xl font-semibold tabular-nums mt-1">{stats.paidActive}</p>
            </div>
            <div className="rounded-xl border border-border/60 bg-muted/20 p-4">
              <p className="text-[10px] uppercase tracking-widest text-muted-foreground font-bold">{t('admin.billing.statTrialing')}</p>
              <p className="text-2xl font-semibold tabular-nums mt-1">{stats.trialing}</p>
            </div>
            <div className="rounded-xl border border-border/60 bg-muted/20 p-4">
              <p className="text-[10px] uppercase tracking-widest text-muted-foreground font-bold">{t('admin.billing.statPastDue')}</p>
              <p className="text-2xl font-semibold tabular-nums mt-1">{stats.pastDue}</p>
            </div>
            <div className="rounded-xl border border-border/60 bg-muted/20 p-4">
              <p className="text-[10px] uppercase tracking-widest text-muted-foreground font-bold">{t('admin.billing.statCanceling')}</p>
              <p className="text-2xl font-semibold tabular-nums mt-1">{stats.cancelAtPeriodEnd}</p>
            </div>
          </div>
          <div className="px-6 pb-4 grid gap-4 sm:grid-cols-2">
            <div>
              <h3 className="text-sm font-medium mb-2">{t('admin.billing.byTier')}</h3>
              <ul className="space-y-1.5 text-sm">
                {Object.entries(stats.byTier).map(([tier, count]) => (
                  <li key={tier} className="flex justify-between border-b border-border/40 pb-1">
                    <span>{tier}</span>
                    <span className="tabular-nums text-muted-foreground">{count}</span>
                  </li>
                ))}
                <li className="flex justify-between text-xs text-muted-foreground pt-1">
                  <span>{t('admin.billing.usersWithoutSub')}</span>
                  <span className="tabular-nums">{stats.usersWithoutSub}</span>
                </li>
              </ul>
            </div>
            <div>
              <h3 className="text-sm font-medium mb-2">{t('admin.billing.byStatus')}</h3>
              <ul className="space-y-1.5 text-sm">
                {Object.keys(stats.byStatus).length === 0 ? (
                  <li className="text-muted-foreground text-xs">{t('admin.billing.noSubs')}</li>
                ) : (
                  Object.entries(stats.byStatus).map(([status, count]) => (
                    <li key={status} className="flex justify-between border-b border-border/40 pb-1">
                      <span>{status}</span>
                      <span className="tabular-nums text-muted-foreground">{count}</span>
                    </li>
                  ))
                )}
              </ul>
            </div>
          </div>
          <div className="px-6 pb-6">
            <h3 className="text-sm font-medium mb-2">{t('admin.billing.recentSubs')}</h3>
            {stats.recent.length === 0 ? (
              <p className="text-sm text-muted-foreground">{t('admin.billing.noSubs')}</p>
            ) : (
              <div className="overflow-x-auto rounded-xl border border-border/60">
                <table className="w-full text-xs">
                  <thead className="bg-muted/40 text-muted-foreground">
                    <tr>
                      <th className="text-start p-2.5 font-medium">{t('admin.billing.colUser')}</th>
                      <th className="text-start p-2.5 font-medium">{t('admin.billing.colTier')}</th>
                      <th className="text-start p-2.5 font-medium">{t('admin.billing.colStatus')}</th>
                      <th className="text-start p-2.5 font-medium">{t('admin.billing.colPeriod')}</th>
                    </tr>
                  </thead>
                  <tbody>
                    {stats.recent.map((row) => (
                      <tr key={`${row.email}-${row.updatedAt}`} className="border-t border-border/50">
                        <td className="p-2.5 truncate max-w-[200px]">{row.email}</td>
                        <td className="p-2.5">{row.tier}</td>
                        <td className="p-2.5">
                          {row.status}
                          {row.cancelAtPeriodEnd ? ` · ${t('admin.billing.canceling')}` : ''}
                          {!row.hasStripeSub ? ` · ${t('admin.billing.manualTier')}` : ''}
                        </td>
                        <td className="p-2.5 text-muted-foreground">
                          {row.trialEndsAt
                            ? t('admin.billing.trialUntil', { date: formatStableUtc(row.trialEndsAt) })
                            : row.currentPeriodEnd
                              ? formatStableUtc(row.currentPeriodEnd)
                              : '—'}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        </div>
      )}

      {/* How to test Stripe */}
      <div className="bg-card rounded-lg border border-border shadow-sm overflow-hidden">
        <button
          type="button"
          onClick={() => setShowTestGuide((v) => !v)}
          className="w-full flex items-center gap-3 p-6 border-b border-border text-start hover:bg-muted/20 transition-colors"
        >
          <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <BookOpen className="h-5 w-5" />
          </div>
          <div className="flex-1">
            <h2 className="font-semibold">{t('admin.billing.testGuideTitle')}</h2>
            <p className="text-sm text-muted-foreground">{t('admin.billing.testGuideDescription')}</p>
          </div>
          {showTestGuide ? <ChevronUp className="h-4 w-4 text-muted-foreground" /> : <ChevronDown className="h-4 w-4 text-muted-foreground" />}
        </button>
        {showTestGuide && (
          <div className="p-6 space-y-3 text-sm text-muted-foreground leading-relaxed">
            <ol className="list-decimal ps-5 space-y-2">
              <li>{t('admin.billing.testStep1')}</li>
              <li>{t('admin.billing.testStep2')}</li>
              <li>
                <code className="text-[11px] bg-muted px-1.5 py-0.5 rounded">stripe listen --forward-to localhost:3000/api/billing/webhook</code>
                {' — '}{t('admin.billing.testStep3')}
              </li>
              <li>{t('admin.billing.testStep4')}</li>
              <li>{t('admin.billing.testStep5')}</li>
              <li>{t('admin.billing.testStep6')}</li>
            </ol>
            <p className="text-xs border-t border-border/50 pt-3">
              {t('admin.billing.testCardHint')}
            </p>
          </div>
        )}
      </div>

      <div className="bg-card rounded-lg border border-border shadow-sm overflow-hidden">
        <div className="flex items-center gap-3 p-6 border-b border-border">
          <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <CreditCard className="h-5 w-5" />
          </div>
          <div>
            <h2 className="font-semibold">{t('admin.billing.stripeConfigTitle')}</h2>
            <p className="text-sm text-muted-foreground">{t('admin.billing.stripeConfigDescription')}</p>
          </div>
        </div>
        <form onSubmit={(e) => { e.preventDefault(); handleSaveBilling(new FormData(e.currentTarget)) }} className="p-6 space-y-6">
          <div className="flex items-center space-x-2">
            <Checkbox
              id="BILLING_ENABLED"
              checked={billingEnabled}
              onCheckedChange={(c) => setBillingEnabled(!!c)}
            />
            <Label htmlFor="BILLING_ENABLED">{t('admin.billing.enableBilling')}</Label>
          </div>
          <div>
            <h3 className="text-sm font-medium mb-3">{t('admin.billing.subscriptionPricesTitle')}</h3>
            <div className="grid gap-4 sm:grid-cols-2">
              {SUBSCRIPTION_PRICE_KEYS.map((key) => {
                const meta = priceMap[key]
                return (
                  <div key={key} className="space-y-2">
                    <Label htmlFor={key}>{t(`admin.billing.${key}`)}</Label>
                    <Input
                      id={key}
                      name={key}
                      defaultValue={initialData.billingConfig[key] ?? ''}
                      placeholder="price_..."
                    />
                    {meta?.stripeAmount != null && (
                      <p className="text-[11px] text-muted-foreground">
                        Stripe: {meta.stripeAmount.toLocaleString('fr-FR', { minimumFractionDigits: 2 })} {meta.stripeCurrency}
                      </p>
                    )}
                    {meta?.error && (
                      <p className="text-[11px] text-rose-600">{meta.error}</p>
                    )}
                  </div>
                )
              })}
            </div>
          </div>
          <div className="border-t border-border/50 pt-4">
            <div className="flex items-center gap-2 mb-1">
              <Package className="h-4 w-4 text-muted-foreground" />
              <h3 className="text-sm font-medium">{t('admin.billing.packPricesTitle')}</h3>
            </div>
            <p className="text-xs text-muted-foreground mb-3">{t('admin.billing.packPricesDescription')}</p>
            <div className="grid gap-4 sm:grid-cols-3">
              {PACK_PRICE_KEYS.map((key) => (
                <div key={key} className="space-y-2">
                  <Label htmlFor={key}>{t(`admin.billing.${key}`)}</Label>
                  <Input
                    id={key}
                    name={key}
                    defaultValue={initialData.billingConfig[key] ?? ''}
                    placeholder="price_..."
                  />
                </div>
              ))}
            </div>
          </div>
          <p className="text-xs text-muted-foreground">{t('admin.billing.secretsNote')}</p>
          <Button type="submit" disabled={isSavingBilling}>{t('admin.billing.saveConfig')}</Button>
        </form>
      </div>

      <div className="bg-card rounded-lg border border-border shadow-sm overflow-hidden">
        <div className="flex items-center gap-3 p-6 border-b border-border">
          <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <Coins className="h-5 w-5" />
          </div>
          <div>
            <h2 className="font-semibold">{t('admin.billing.creditsTitle')}</h2>
            <p className="text-sm text-muted-foreground">{t('admin.billing.creditsDescription')}</p>
          </div>
        </div>
        <div className="p-6 space-y-4">
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            {(initialData.creditAllocations ?? []).map((row) => (
              <div
                key={row.tier}
                className="rounded-xl border border-border/60 bg-muted/30 p-4 space-y-1"
              >
                <p className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground">
                  {row.tier}
                </p>
                <p className="text-2xl font-semibold tabular-nums">
                  {row.unlimited
                    ? t('admin.billing.modeUnlimited')
                    : row.monthlyCredits?.toLocaleString('fr-FR')}
                </p>
                {!row.unlimited && (
                  <p className="text-[11px] text-muted-foreground">
                    {t('admin.billing.creditsPerMonth')}
                  </p>
                )}
              </div>
            ))}
          </div>
          {(initialData.creditPacks?.length ?? 0) > 0 && (
            <div className="border-t border-border/40 pt-3">
              <p className="text-xs font-medium mb-2">{t('admin.billing.packsCatalogTitle')}</p>
              <div className="flex flex-wrap gap-2">
                {(initialData.creditPacks ?? []).map((pack) => (
                  <span
                    key={pack.id}
                    className="inline-flex items-center gap-1.5 rounded-lg border border-border/60 bg-muted/20 px-3 py-1.5 text-xs"
                  >
                    <span className="font-semibold uppercase">{pack.id}</span>
                    <span className="text-muted-foreground">
                      {pack.credits.toLocaleString('fr-FR')} cr. · {pack.defaultDisplay}
                    </span>
                  </span>
                ))}
              </div>
            </div>
          )}
          <p className="text-xs text-muted-foreground leading-relaxed border-t border-border/40 pt-3">
            {t('admin.billing.creditsCostsNote')}
          </p>
          <p className="text-xs text-muted-foreground">
            {t('admin.billing.creditsResetHint')}
          </p>
        </div>
      </div>

      <div className="bg-card rounded-lg border border-border shadow-sm overflow-hidden">
        <div className="flex items-center gap-3 p-6 border-b border-border">
          <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center text-primary">
            <Gauge className="h-5 w-5" />
          </div>
          <div>
            <h2 className="font-semibold">{t('admin.billing.usageTitle')}</h2>
            <p className="text-sm text-muted-foreground">
              {t('admin.billing.usagePeriod', { period: initialData.usageOverview.period })}
              {initialData.usageOverview.lastSyncedAt
                ? ` · ${t('admin.billing.lastSync', {
                    date: formatStableUtc(initialData.usageOverview.lastSyncedAt),
                  })}`
                : ` · ${t('admin.billing.notSynced')}`}
            </p>
          </div>
        </div>
        <div className="p-6 grid gap-6 lg:grid-cols-2">
          <div>
            <h3 className="text-sm font-medium mb-3">{t('admin.billing.byFeature')}</h3>
            {initialData.usageOverview.byFeature.length === 0 ? (
              <p className="text-sm text-muted-foreground">{t('admin.billing.noUsageData')}</p>
            ) : (
              <ul className="space-y-2 text-sm">
                {initialData.usageOverview.byFeature.map((row) => (
                  <li key={row.feature} className="flex justify-between gap-4 border-b border-border/50 pb-2">
                    <span className="font-mono text-xs">{row.feature}</span>
                    <span className="text-muted-foreground">{row.requests} req · {row.tokens} tok</span>
                  </li>
                ))}
              </ul>
            )}
          </div>
          <div>
            <h3 className="text-sm font-medium mb-3">{t('admin.billing.topUsers')}</h3>
            {initialData.usageOverview.topUsers.length === 0 ? (
              <p className="text-sm text-muted-foreground">{t('admin.billing.noUsageData')}</p>
            ) : (
              <ul className="space-y-2 text-sm">
                {initialData.usageOverview.topUsers.map((row) => (
                  <li key={row.userId} className="flex justify-between gap-4 border-b border-border/50 pb-2">
                    <span className="truncate">{row.email}</span>
                    <span className="text-muted-foreground shrink-0">{row.requests} req</span>
                  </li>
                ))}
              </ul>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}
