import React, { useEffect, useState } from 'react';
import ComponentCard from '../../components/common/ComponentCard';
import Badge from '../../components/ui/badge/Badge';
import { useToast } from '../../components/ui/toast/ToastContainer';
import { getCreditTransactions, type CreditTransaction } from '../../services/billing.api';

type Variant = 'card' | 'plain';

export default function BillingRecentTransactions({ limit = 10, variant = 'card' }: { limit?: number; variant?: Variant }) {
  const toast = useToast();
  const [transactions, setTransactions] = useState<CreditTransaction[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    load();
  }, []);

  const load = async () => {
    try {
      setLoading(true);
      const res = await getCreditTransactions();
      setTransactions(res.results || []);
    } catch (err: any) {
      toast?.error(err?.message || 'Failed to load transactions');
    } finally {
      setLoading(false);
    }
  };

  const getTransactionTypeColor = (type: string) => {
    switch (type) {
      case 'purchase': return 'success';
      case 'grant': return 'info';
      case 'deduction': return 'warning';
      case 'usage': return 'error';
      case 'refund': return 'primary';
      case 'adjustment': return 'secondary';
      default: return 'default';
    }
  };

  const formatOperationType = (type: string) => {
    return type.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
  };

  const content = (
    <div className="space-y-3">
      {transactions.slice(0, limit).map((transaction) => (
        <div key={transaction.id} className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
          <div className="flex-1">
            <div className="flex items-center gap-2">
              <Badge tone={getTransactionTypeColor(transaction.transaction_type) as any}>
                {formatOperationType(transaction.transaction_type)}
              </Badge>
              <span className="text-sm text-gray-900 dark:text-white">
                {transaction.description}
              </span>
            </div>
            <div className="text-xs text-gray-500 dark:text-gray-400 mt-1">
              {new Date(transaction.created_at).toLocaleString()}
              {transaction.reference_id && ` • Ref: ${transaction.reference_id}`}
            </div>
          </div>
          <div className="text-right">
            <div className={`font-bold ${transaction.amount > 0 ? 'text-green-600' : 'text-red-600'}`}>
              {transaction.amount > 0 ? '+' : ''}{transaction.amount}
            </div>
          </div>
        </div>
      ))}
      {transactions.length === 0 && (
        <div className="text-center py-8 text-gray-500 dark:text-gray-400">No transactions yet</div>
      )}
    </div>
  );

  if (variant === 'plain') {
    if (loading) {
      return <div className="text-center py-8 text-gray-500">Loading...</div>;
    }
    return content;
  }

  if (loading) {
    return (
      <ComponentCard title="Recent Transactions">
        <div className="text-center py-8 text-gray-500">Loading...</div>
      </ComponentCard>
    );
  }

  return <ComponentCard title="Recent Transactions">{content}</ComponentCard>;
}
