'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 } from 'lucide-react'

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[]
  /** Allocations mensuelles du solde unique (source de vérité débit) */
  creditAllocations?: Array<{
    tier: string
    monthlyCredits: number | null
    unlimited: boolean
  }>
  creditCosts?: Record<string, number>
  creditPacks?: Array<{
    id: string
    credits: number
    defaultDisplay: 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

/** Date stable SSR/client (pas de toLocaleString — mismatch locale + fuseau). */
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`
}

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

  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)
    }
  }

  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>

      <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) => (
                <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>
          <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>

      {/* Solde unique — source de vérité du débit */}
      <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', {
                    // Format fixe UTC (évite mismatch SSR locale/fuseau vs client)
                    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>
  )
}
