'use client';

import { ExternalLink, Receipt } from 'lucide-react';
import { useState } from 'react';
import { Loader2 } from 'lucide-react';
import { useLanguage } from '@/lib/i18n';

export function BillingHistory() {
  const { t } = useLanguage();
  const [loading, setLoading] = useState(false);

  const handleOpenPortal = async () => {
    setLoading(true);
    try {
      const res = await fetch('/api/billing/portal', { method: 'POST' });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error ?? 'Failed');
      window.location.href = data.url;
    } catch {
      // ignore — portal not configured
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="rounded-xl border border-border/40 bg-paper p-6 space-y-4">
      <div className="flex items-center gap-2">
        <Receipt className="h-4 w-4 text-muted-foreground" />
        <h3 className="text-sm font-semibold text-foreground">{t('billing.billingHistory')}</h3>
      </div>
      <p className="text-xs text-muted-foreground">{t('billing.noUsage')}</p>
      <button
        type="button"
        onClick={handleOpenPortal}
        disabled={loading}
        className="flex items-center gap-2 text-xs text-muted-foreground hover:text-foreground transition-colors disabled:opacity-60"
      >
        {loading ? (
          <Loader2 className="h-3.5 w-3.5 animate-spin" />
        ) : (
          <ExternalLink className="h-3.5 w-3.5" />
        )}
        {t('billing.viewInvoices')}
      </button>
    </div>
  );
}
