/**
 * Credits & Billing Page
 * User-facing credits usage, transactions, and billing information
 */
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import PageMeta from '../../components/common/PageMeta';
import ComponentCard from '../../components/common/ComponentCard';
import EnhancedMetricCard from '../../components/dashboard/EnhancedMetricCard';
import { useToast } from '../../components/ui/toast/ToastContainer';
import { getCreditBalance, getCreditTransactions, CreditBalance, CreditTransaction } from '../../services/billing.api';
import Button from '../../components/ui/button/Button';
import Badge from '../../components/ui/badge/Badge';
import { 
  BoltIcon, 
  DollarLineIcon, 
  TimeIcon, 
  CheckCircleIcon 
} from '../../icons';

const CreditsAndBilling: React.FC = () => {
  const toast = useToast();
  const [balance, setBalance] = useState<CreditBalance | null>(null);
  const [transactions, setTransactions] = useState<CreditTransaction[]>([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState<'overview' | 'transactions'>('overview');

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

  const loadData = async () => {
    try {
      setLoading(true);
      const [balanceData, transactionsData] = await Promise.all([
        getCreditBalance(),
        getCreditTransactions(),
      ]);
      
      setBalance(balanceData);
      setTransactions(transactionsData.results || []);
    } catch (error: any) {
      toast?.error(error?.message || 'Failed to load billing data');
    } 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(' ');
  };

  if (loading) {
    return (
      <div className="p-6">
        <PageMeta title="Credits & Billing" description="Manage your credits and billing" />
        <div className="text-center py-12">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600 mx-auto"></div>
          <p className="mt-4 text-gray-600 dark:text-gray-400">Loading billing data...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="p-6">
      <PageMeta title="Credits & Billing" description="Manage your credits and billing" />
      
      <div className="flex items-center justify-between mb-6">
        <div>
          <h1 className="text-3xl font-bold text-gray-900 dark:text-white">Credits & Billing</h1>
          <p className="text-gray-600 dark:text-gray-400 mt-1">
            Manage your credits, view transactions, and monitor usage
          </p>
        </div>
        <Link to="/account/purchase-credits">
          <Button variant="primary">
            Purchase Credits
          </Button>
        </Link>
      </div>

      {/* Credit Balance Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <EnhancedMetricCard
          title="Current Balance"
          value={balance?.balance || 0}
          icon={<BoltIcon />}
          accentColor="orange"
        />
        <EnhancedMetricCard
          title="Monthly Credits"
          value={balance?.monthly_credits || 0}
          subtitle={balance?.subscription_plan || 'No plan'}
          icon={<CheckCircleIcon />}
          accentColor="green"
        />
        <EnhancedMetricCard
          title="Subscription"
          value={balance?.subscription_plan || 'None'}
          subtitle={balance?.subscription_status || 'Inactive'}
          icon={<DollarLineIcon />}
          accentColor="blue"
        />
        <EnhancedMetricCard
          title="Total Transactions"
          value={transactions.length}
          icon={<TimeIcon />}
          accentColor="purple"
        />
      </div>

      {/* Tabs */}
      <div className="mb-6 border-b border-gray-200 dark:border-gray-700">
        <nav className="-mb-px flex space-x-8">
          <button
            onClick={() => setActiveTab('overview')}
            className={`py-4 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'overview'
                ? 'border-primary-500 text-primary-600 dark:text-primary-400'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300'
            }`}
          >
            Overview
          </button>
          <button
            onClick={() => setActiveTab('transactions')}
            className={`py-4 px-1 border-b-2 font-medium text-sm ${
              activeTab === 'transactions'
                ? 'border-primary-500 text-primary-600 dark:text-primary-400'
                : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 dark:text-gray-400 dark:hover:text-gray-300'
            }`}
          >
            Transactions ({transactions.length})
          </button>
        </nav>
      </div>

      {/* Tab Content */}
      {activeTab === 'overview' && (
        <div className="grid grid-cols-1 lg:grid-cols-1 gap-6">
          {/* Recent Transactions */}
          <ComponentCard title="Recent Transactions">
            <div className="space-y-3">
              {transactions.slice(0, 10).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>
          </ComponentCard>
        </div>
      )}

      {activeTab === 'transactions' && (
        <ComponentCard title="All Transactions">
          <div className="overflow-x-auto">
            <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
              <thead className="bg-gray-50 dark:bg-gray-800">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    Date
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    Type
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    Description
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    Reference
                  </th>
                  <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                    Amount
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white dark:bg-gray-900 divide-y divide-gray-200 dark:divide-gray-700">
                {transactions.map((transaction) => (
                  <tr key={transaction.id}>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                      {new Date(transaction.created_at).toLocaleDateString()}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <Badge tone={getTransactionTypeColor(transaction.transaction_type) as any}>
                        {formatOperationType(transaction.transaction_type)}
                      </Badge>
                    </td>
                    <td className="px-6 py-4 text-sm text-gray-900 dark:text-white">
                      {transaction.description}
                    </td>
                    <td className="px-6 py-4 text-sm text-gray-500 dark:text-gray-400">
                      {transaction.reference_id || '-'}
                    </td>
                    <td className={`px-6 py-4 whitespace-nowrap text-sm text-right font-bold ${
                      transaction.amount > 0 ? 'text-green-600' : 'text-red-600'
                    }`}>
                      {transaction.amount > 0 ? '+' : ''}{transaction.amount}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </ComponentCard>
      )}
    </div>
  );
};

export default CreditsAndBilling;
