'use client';

import { useQuery } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
import Link from 'next/link';
import { apiClient } from '@/infrastructure/api/api-client';
import { CreditCard, Zap, TrendingUp, AlertCircle, ChevronRight } from 'lucide-react';

interface Subscription {
  id: string;
  status: string;
  plan: { name: string; displayName: string } | null;
  nextPlan: { name: string; displayName: string } | null;
  currentPeriodStart: string;
  currentPeriodEnd: string;
  trialEndsAt: string | null;
  cancelAtPeriodEnd: boolean;
}

interface QuotaStatus {
  allowed: boolean;
  remaining: number;
  usedTokens: number;
  limitTokens: number;
  isHardLimit: boolean;
  overageAllowed: boolean;
}

interface Invoice {
  id: string;
  invoiceNumber: string;
  status: string;
  currency: string;
  totalAmount: number;
  amountDue: number;
  periodStart: string;
  periodEnd: string;
  dueDate: string;
  paidAt: string | null;
  createdAt: string;
}

function StatusBadge({ status }: { status: string }) {
  const colors: Record<string, string> = {
    active: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
    trialing: 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400',
    past_due: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
    cancelled: 'bg-gray-100 text-gray-600 dark:bg-gray-800 dark:text-gray-400',
    expired: 'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-400',
    paid: 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400',
    open: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400',
  };
  return (
    <span className={`inline-block px-2 py-0.5 rounded text-xs font-medium ${colors[status] ?? 'bg-muted text-muted-foreground'}`}>
      {status}
    </span>
  );
}

function UsageBar({ used, limit }: { used: number; limit: number }) {
  const pct = limit <= 0 ? 0 : Math.min(100, (used / limit) * 100);
  const color = pct >= 90 ? 'bg-red-500' : pct >= 70 ? 'bg-yellow-500' : 'bg-green-500';
  return (
    <div className="w-full bg-muted rounded-full h-2">
      <div className={`${color} h-2 rounded-full transition-all`} style={{ width: `${pct}%` }} />
    </div>
  );
}

function formatTokens(n: number) {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(2)}M`;
  if (n >= 1_000) return `${(n / 1_000).toFixed(0)}K`;
  return `${n}`;
}

export default function BillingPage() {
  const { t } = useTranslation('billing');

  const { data: sub } = useQuery<Subscription>({
    queryKey: ['billing', 'subscription'],
    queryFn: () => apiClient('/api/v1/billing/subscription'),
    retry: false,
  });

  const { data: quota } = useQuery<QuotaStatus>({
    queryKey: ['billing', 'quota'],
    queryFn: () => apiClient('/api/v1/billing/usage/current'),
    refetchInterval: 60_000,
  });

  const { data: invoicesData } = useQuery<{ data: Invoice[]; total: number }>({
    queryKey: ['billing', 'invoices'],
    queryFn: () => apiClient('/api/v1/billing/invoices?limit=5'),
  });

  const recentInvoices = invoicesData?.data ?? [];
  const usedPct = quota && quota.limitTokens > 0
    ? Math.min(100, (quota.usedTokens / quota.limitTokens) * 100)
    : 0;

  return (
    <div className="space-y-6">
      <h1 className="text-2xl font-bold">{t('overview.title')}</h1>

      {/* Usage Warning Banner */}
      {usedPct >= 80 && (
        <div className="flex items-center gap-3 p-4 rounded-lg bg-yellow-50 border border-yellow-200 dark:bg-yellow-900/20 dark:border-yellow-800">
          <AlertCircle className="h-5 w-5 text-yellow-600 flex-shrink-0" />
          <span className="text-sm text-yellow-800 dark:text-yellow-300">
            {t('overview.usageWarning', { pct: usedPct.toFixed(0) })}{' '}
            {usedPct >= 100 ? t('overview.limitReached') : t('overview.considerUpgrade')}
          </span>
          <Link href="/billing/plans" className="ml-auto text-sm font-medium text-yellow-800 dark:text-yellow-300 underline whitespace-nowrap">
            {t('overview.upgrade')}
          </Link>
        </div>
      )}

      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* Subscription Card */}
        <div className="rounded-lg border bg-card p-6 space-y-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <CreditCard className="h-5 w-5 text-muted-foreground" />
              <h2 className="font-semibold">{t('overview.currentPlan')}</h2>
            </div>
            <Link href="/billing/plans" className="text-sm text-primary flex items-center gap-1 hover:underline">
              {t('overview.change')} <ChevronRight className="h-4 w-4" />
            </Link>
          </div>

          {sub ? (
            <div className="space-y-2">
              <div className="flex items-center gap-3">
                <span className="text-2xl font-bold capitalize">{sub.plan?.displayName ?? 'Unknown'}</span>
                <StatusBadge status={sub.status} />
              </div>
              {sub.trialEndsAt && sub.status === 'trialing' && (
                <p className="text-sm text-muted-foreground">
                  {t('overview.trialEnds', { date: new Date(sub.trialEndsAt).toLocaleDateString() })}
                </p>
              )}
              {sub.cancelAtPeriodEnd && (
                <p className="text-sm text-yellow-600 dark:text-yellow-400">
                  {t('overview.cancelsOn', { date: new Date(sub.currentPeriodEnd).toLocaleDateString() })}
                </p>
              )}
              {sub.nextPlan && (
                <p className="text-sm text-muted-foreground">
                  {t('overview.downgradeTo', {
                    plan: sub.nextPlan.displayName,
                    date: new Date(sub.currentPeriodEnd).toLocaleDateString(),
                  })}
                </p>
              )}
              <p className="text-xs text-muted-foreground">
                {t('overview.period', {
                  start: new Date(sub.currentPeriodStart).toLocaleDateString(),
                  end: new Date(sub.currentPeriodEnd).toLocaleDateString(),
                })}
              </p>
            </div>
          ) : (
            <p className="text-muted-foreground text-sm">{t('overview.noSubscription')}</p>
          )}
        </div>

        {/* Token Usage Card */}
        <div className="rounded-lg border bg-card p-6 space-y-4">
          <div className="flex items-center gap-2">
            <Zap className="h-5 w-5 text-muted-foreground" />
            <h2 className="font-semibold">{t('overview.tokenUsage')}</h2>
          </div>

          {quota ? (
            <div className="space-y-3">
              <div className="flex justify-between text-sm">
                <span className="font-medium">{t('overview.tokensUsed', { used: formatTokens(quota.usedTokens) })}</span>
                <span className="text-muted-foreground">
                  {quota.limitTokens === -1
                    ? t('overview.unlimited')
                    : t('overview.tokensLimit', { limit: formatTokens(quota.limitTokens) })}
                </span>
              </div>
              {quota.limitTokens !== -1 && (
                <UsageBar used={quota.usedTokens} limit={quota.limitTokens} />
              )}
              <div className="flex justify-between text-xs text-muted-foreground">
                <span>{usedPct.toFixed(1)}%</span>
                {quota.overageAllowed && usedPct > 100 && (
                  <span className="text-yellow-600">{t('overview.overageApply')}</span>
                )}
              </div>
            </div>
          ) : (
            <p className="text-muted-foreground text-sm">{t('overview.loadingUsage')}</p>
          )}
        </div>
      </div>

      {/* Recent Invoices */}
      <div className="rounded-lg border bg-card">
        <div className="flex items-center justify-between p-6 border-b">
          <div className="flex items-center gap-2">
            <TrendingUp className="h-5 w-5 text-muted-foreground" />
            <h2 className="font-semibold">{t('overview.recentInvoices')}</h2>
          </div>
          <Link href="/billing/invoices" className="text-sm text-primary hover:underline flex items-center gap-1">
            {t('overview.viewAll')} <ChevronRight className="h-4 w-4" />
          </Link>
        </div>

        {recentInvoices.length === 0 ? (
          <div className="p-6 text-center text-muted-foreground text-sm">{t('overview.noInvoices')}</div>
        ) : (
          <div className="divide-y">
            {recentInvoices.map((inv) => (
              <Link key={inv.id} href={`/billing/invoices/${inv.id}`} className="flex items-center justify-between p-4 hover:bg-muted/50 transition-colors">
                <div>
                  <p className="text-sm font-medium">{inv.invoiceNumber}</p>
                  <p className="text-xs text-muted-foreground">
                    {new Date(inv.periodStart).toLocaleDateString()} – {new Date(inv.periodEnd).toLocaleDateString()}
                  </p>
                </div>
                <div className="flex items-center gap-3">
                  <span className="text-sm font-medium">{inv.currency} {inv.totalAmount.toFixed(2)}</span>
                  <StatusBadge status={inv.status} />
                </div>
              </Link>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
