/**
 * Billing Mandate View Page
 * 
 * Shows mandate-level balances and transactions for SysAdmins.
 * Includes filtering by mandate.
 */

import React, { useEffect, useState, useMemo } from 'react';
import { useApiRequest } from '../../hooks/useApi';
import {
  fetchMandateViewBalances,
  fetchMandateViewTransactions,
  type MandateBalance,
  type BillingTransaction
} from '../../api/billingApi';
import { BillingNav } from './BillingNav';
import styles from './Billing.module.css';

import { useLanguage } from '../../providers/language/LanguageContext';

// ============================================================================
// MANDATE BALANCE TABLE
// ============================================================================

interface MandateBalanceTableProps {
  balances: MandateBalance[];
  selectedMandateId: string | null;
  onSelectMandate: (mandateId: string | null) => void;
}

const MandateBalanceTable: React.FC<MandateBalanceTableProps> = ({ balances,
  selectedMandateId,
  onSelectMandate
}) => {
  const { t } = useLanguage();
  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('de-CH', {
      style: 'currency',
      currency: 'CHF'
    }).format(amount);
  };

  return (
    <div style={{ overflowX: 'auto' }}>
      <table className={styles.transactionsTable}>
        <thead>
          <tr>
            <th>{t('Mandant')}</th>
            <th>{t('Anzahl Benutzer')}</th>
            <th>{t('Warnschwelle')}</th>
            <th style={{ textAlign: 'right' }}>{t('Gesamtguthaben')}</th>
            <th>{t('Aktion')}</th>
          </tr>
        </thead>
        <tbody>
          {balances.map((balance) => (
            <tr 
              key={balance.mandateId}
              className={selectedMandateId === balance.mandateId ? styles.selectedRow : ''}
            >
              <td>{balance.mandateName || balance.mandateId}</td>
              <td>{balance.userCount}</td>
              <td>{balance.warningThresholdPercent}%</td>
              <td style={{ textAlign: 'right' }}>{formatCurrency(balance.totalBalance)}</td>
              <td>
                <button
                  className={`${styles.button} ${styles.buttonSecondary}`}
                  onClick={() => onSelectMandate(
                    selectedMandateId === balance.mandateId ? null : balance.mandateId
                  )}
                  style={{ padding: '4px 8px', fontSize: '12px' }}
                >
                  {selectedMandateId === balance.mandateId ? t('Alle') : t('Filter')}
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

// ============================================================================
// TRANSACTION TABLE
// ============================================================================

interface TransactionTableProps {
  transactions: BillingTransaction[];
}

const TransactionTable: React.FC<TransactionTableProps> = ({ transactions }) => {
  const { t } = useLanguage();
  const formatCurrency = (amount: number) => {
    return new Intl.NumberFormat('de-CH', {
      style: 'currency',
      currency: 'CHF'
    }).format(amount);
  };

  const formatDate = (dateString?: string) => {
    if (!dateString) return '-';
    return new Date(dateString).toLocaleString('de-CH', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const getTypeClass = (type: string) => {
    switch (type) {
      case 'CREDIT': return styles.credit;
      case 'DEBIT': return styles.debit;
      case 'ADJUSTMENT': return styles.adjustment;
      default: return '';
    }
  };

  const getTypeLabel = (type: string) => {
    switch (type) {
      case 'CREDIT': return 'Gutschrift';
      case 'DEBIT': return 'Belastung';
      case 'ADJUSTMENT': return 'Korrektur';
      default: return type;
    }
  };

  return (
    <div style={{ overflowX: 'auto' }}>
      <table className={styles.transactionsTable}>
        <thead>
          <tr>
            <th>Datum</th>
            <th>{t('Mandant')}</th>
            <th>Typ</th>
            <th>{t('Beschreibung')}</th>
            <th>Anbieter</th>
            <th>Modell</th>
            <th>Feature</th>
            <th style={{ textAlign: 'right' }}>{t('Betrag')}</th>
          </tr>
        </thead>
        <tbody>
          {transactions.map((txn) => (
            <tr key={txn.id}>
              <td>{formatDate(txn.createdAt)}</td>
              <td>{txn.mandateName || '-'}</td>
              <td>
                <span className={`${styles.transactionType} ${getTypeClass(txn.transactionType)}`}>
                  {getTypeLabel(txn.transactionType)}
                </span>
              </td>
              <td>{txn.description}</td>
              <td>{txn.aicoreProvider || '-'}</td>
              <td>{txn.aicoreModel || '-'}</td>
              <td>{txn.featureCode || '-'}</td>
              <td style={{ textAlign: 'right' }}>
                {txn.transactionType === 'DEBIT' ? '-' : '+'}{formatCurrency(txn.amount)}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

// ============================================================================
// MAIN COMPONENT
// ============================================================================

interface BillingMandateViewProps {
  embedded?: boolean;
}

export const BillingMandateView: React.FC<BillingMandateViewProps> = ({ embedded = false }) => {
  const { t } = useLanguage();
  const { request, isLoading: loading } = useApiRequest();
  const [balances, setBalances] = useState<MandateBalance[]>([]);
  const [transactions, setTransactions] = useState<BillingTransaction[]>([]);
  const [selectedMandateId, setSelectedMandateId] = useState<string | null>(null);
  const [limit, setLimit] = useState(100);

  // Load data
  useEffect(() => {
    const loadData = async () => {
      try {
        const [balanceData, transactionData] = await Promise.all([
          fetchMandateViewBalances(request),
          fetchMandateViewTransactions(request, limit)
        ]);
        setBalances(Array.isArray(balanceData) ? balanceData : []);
        setTransactions(Array.isArray(transactionData) ? transactionData : []);
      } catch (err) {
        console.error('Error loading mandate view data:', err);
        setBalances([]);
        setTransactions([]);
      }
    };
    loadData();
  }, [request, limit]);

  // Filter transactions by selected mandate
  const filteredTransactions = useMemo(() => {
    if (!selectedMandateId) return transactions;
    return transactions.filter(tx => tx.mandateId === selectedMandateId);
  }, [transactions, selectedMandateId]);

  const handleLoadMore = () => {
    setLimit(prev => prev + 100);
  };

  return (
    <div className={embedded ? '' : styles.billingDashboard}>
      {!embedded && (
        <>
          <header className={styles.pageHeader}>
            <h1>{t('Mandanten-Billing')}</h1>
            <p className={styles.subtitle}>{t('Guthaben und Transaktionen pro Mandant')}</p>
          </header>

          <BillingNav />
        </>
      )}

      {/* Mandate Balances */}
      <section className={styles.section}>
        <h2 className={styles.sectionTitle}>{t('Mandanten-Guthaben')}</h2>
        {loading && balances.length === 0 ? (
          <div className={styles.loadingPlaceholder}>{t('Daten laden')}</div>
        ) : balances.length === 0 ? (
          <div className={styles.noData}>{t('Keine Mandanten mit Billing-Einstellungen vorhanden')}</div>
        ) : (
          <MandateBalanceTable
            balances={balances}
            selectedMandateId={selectedMandateId}
            onSelectMandate={setSelectedMandateId}
          />
        )}
      </section>

      {/* Transactions */}
      <section className={styles.section}>
        <div className={styles.sectionHeader}>
          <h2 className={styles.sectionTitle}>
            {t('Transaktionen')}
            {selectedMandateId && (
              <span style={{ fontWeight: 'normal', fontSize: '14px', marginLeft: '8px' }}>
                {t('(gefiltert nach {name})', {
                  name: balances.find(b => b.mandateId === selectedMandateId)?.mandateName || selectedMandateId,
                })}
              </span>
            )}
          </h2>
        </div>
        {loading && transactions.length === 0 ? (
          <div className={styles.loadingPlaceholder}>{t('Transaktionen laden')}</div>
        ) : filteredTransactions.length === 0 ? (
          <div className={styles.noData}>{t('Keine Transaktionen vorhanden')}</div>
        ) : (
          <>
            <TransactionTable transactions={filteredTransactions} />
            
            {transactions.length >= limit && (
              <div style={{ textAlign: 'center', marginTop: 'var(--spacing-md)' }}>
                <button
                  className={`${styles.button} ${styles.buttonSecondary}`}
                  onClick={handleLoadMore}
                  disabled={loading}
                >
                  {loading ? t('Laden') : t('Mehr laden')}
                </button>
              </div>
            )}
          </>
        )}
      </section>
    </div>
  );
};

export default BillingMandateView;
