/**
 * Billing User View Page
 * 
 * Shows user-level balances and transactions.
 * RBAC-based: Users see only their own data, Admins see all.
 * Includes filtering by mandate and user.
 */

import React, { useEffect, useState, useMemo } from 'react';
import { useApiRequest } from '../../hooks/useApi';
import {
  fetchUserViewBalances,
  fetchUserViewTransactions,
  type UserBalance,
  type UserTransaction
} from '../../api/billingApi';
import { BillingNav } from './BillingNav';
import styles from './Billing.module.css';

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

// ============================================================================
// USER BALANCE TABLE
// ============================================================================

interface UserBalanceTableProps {
  balances: UserBalance[];
  selectedMandateId: string | null;
  selectedUserId: string | null;
  onSelectMandate: (mandateId: string | null) => void;
  onSelectUser: (userId: string | null) => void;
}

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

  // Get unique mandates and users for filter dropdowns
  const uniqueMandates = useMemo(() => {
    const mandates = new Map<string, string>();
    balances.forEach(b => {
      if (b.mandateId && !mandates.has(b.mandateId)) {
        mandates.set(b.mandateId, b.mandateName || b.mandateId);
      }
    });
    return Array.from(mandates.entries());
  }, [balances]);

  const uniqueUsers = useMemo(() => {
    const users = new Map<string, string>();
    balances.forEach(b => {
      if (b.userId && !users.has(b.userId)) {
        users.set(b.userId, b.userName || b.userId);
      }
    });
    return Array.from(users.entries());
  }, [balances]);

  // Apply filters
  const filteredBalances = useMemo(() => {
    let result = balances;
    if (selectedMandateId) {
      result = result.filter(b => b.mandateId === selectedMandateId);
    }
    if (selectedUserId) {
      result = result.filter(b => b.userId === selectedUserId);
    }
    return result;
  }, [balances, selectedMandateId, selectedUserId]);

  return (
    <>
      {/* Filter Controls */}
      <div className={styles.filterControls} style={{ display: 'flex', gap: '16px', marginBottom: '16px' }}>
        <div>
          <label style={{ display: 'block', marginBottom: '4px', fontSize: '12px', fontWeight: 500 }}>
            {t('Mandant:')}
          </label>
          <select
            value={selectedMandateId || ''}
            onChange={(e) => onSelectMandate(e.target.value || null)}
            className={styles.select}
          >
            <option value="">{t('Alle Mandanten')}</option>
            {uniqueMandates.map(([id, name]) => (
              <option key={id} value={id}>{name}</option>
            ))}
          </select>
        </div>
        <div>
          <label style={{ display: 'block', marginBottom: '4px', fontSize: '12px', fontWeight: 500 }}>
            Benutzer:
          </label>
          <select
            value={selectedUserId || ''}
            onChange={(e) => onSelectUser(e.target.value || null)}
            className={styles.select}
          >
            <option value="">{t('Alle Benutzer')}</option>
            {uniqueUsers.map(([id, name]) => (
              <option key={id} value={id}>{name}</option>
            ))}
          </select>
        </div>
      </div>

      {/* Table */}
      <div style={{ overflowX: 'auto' }}>
        <table className={styles.transactionsTable}>
          <thead>
            <tr>
              <th>{t('Mandant')}</th>
              <th>{t('Benutzer')}</th>
              <th style={{ textAlign: 'right' }}>{t('Guthaben')}</th>
              <th style={{ textAlign: 'right' }}>{t('Warnschwelle')}</th>
              <th>{t('Status')}</th>
            </tr>
          </thead>
          <tbody>
            {filteredBalances.map((balance) => (
              <tr 
                key={balance.accountId}
                className={balance.isWarning ? styles.warningRow : ''}
              >
                <td>{balance.mandateName || balance.mandateId}</td>
                <td>{balance.userName || balance.userId}</td>
                <td style={{ textAlign: 'right' }}>{formatCurrency(balance.balance)}</td>
                <td style={{ textAlign: 'right' }}>{formatCurrency(balance.warningThreshold)}</td>
                <td>
                  {balance.isWarning ? (
                    <span className={styles.warningBadge} style={{ fontSize: '12px', padding: '2px 6px' }}>
                      {t('Niedrig')}
                    </span>
                  ) : balance.enabled ? (
                    <span style={{ color: 'var(--color-success)' }}>{t('Aktiv')}</span>
                  ) : (
                    <span style={{ color: 'var(--color-error)' }}>{t('Deaktiviert')}</span>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
};

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

interface UserTransactionTableProps {
  transactions: UserTransaction[];
  selectedMandateId: string | null;
  selectedUserId: string | null;
}

const UserTransactionTable: React.FC<UserTransactionTableProps> = ({
  transactions,
  selectedMandateId,
  selectedUserId
}) => {
  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;
    }
  };

  // Apply filters
  const filteredTransactions = useMemo(() => {
    let result = transactions;
    if (selectedMandateId) {
      result = result.filter(t => t.mandateId === selectedMandateId);
    }
    if (selectedUserId) {
      result = result.filter(t => t.userId === selectedUserId);
    }
    return result;
  }, [transactions, selectedMandateId, selectedUserId]);

  return (
    <div style={{ overflowX: 'auto' }}>
      <table className={styles.transactionsTable}>
        <thead>
          <tr>
            <th>Datum</th>
            <th>{t('Mandant')}</th>
            <th>{t('Benutzer')}</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>
          {filteredTransactions.map((txn) => (
            <tr key={txn.id}>
              <td>{formatDate(txn.createdAt)}</td>
              <td>{txn.mandateName || '-'}</td>
              <td>{txn.userName || '-'}</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
// ============================================================================

export const BillingUserView: React.FC = () => {
  const { t } = useLanguage();
  const { request, isLoading: loading } = useApiRequest();
  const [balances, setBalances] = useState<UserBalance[]>([]);
  const [transactions, setTransactions] = useState<UserTransaction[]>([]);
  const [selectedMandateId, setSelectedMandateId] = useState<string | null>(null);
  const [selectedUserId, setSelectedUserId] = useState<string | null>(null);
  const [limit, setLimit] = useState(100);

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

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

  // Count filtered transactions for display
  const filteredTransactionCount = useMemo(() => {
    let result = transactions;
    if (selectedMandateId) {
      result = result.filter(t => t.mandateId === selectedMandateId);
    }
    if (selectedUserId) {
      result = result.filter(t => t.userId === selectedUserId);
    }
    return result.length;
  }, [transactions, selectedMandateId, selectedUserId]);

  return (
    <div className={styles.billingDashboard}>
      <header className={styles.pageHeader}>
        <h1>{t('Benutzer-Billing')}</h1>
        <p className={styles.subtitle}>{t('Guthaben und Transaktionen pro Benutzer')}</p>
      </header>

      <BillingNav />

      {/* User Balances */}
      <section className={styles.section}>
        <h2 className={styles.sectionTitle}>{t('Benutzer-Guthaben')}</h2>
        {loading && balances.length === 0 ? (
          <div className={styles.loadingPlaceholder}>{t('Daten laden')}</div>
        ) : balances.length === 0 ? (
          <div className={styles.noData}>{t('Keine Benutzerkonten vorhanden')}</div>
        ) : (
          <UserBalanceTable
            balances={balances}
            selectedMandateId={selectedMandateId}
            selectedUserId={selectedUserId}
            onSelectMandate={setSelectedMandateId}
            onSelectUser={setSelectedUserId}
          />
        )}
      </section>

      {/* Transactions */}
      <section className={styles.section}>
        <div className={styles.sectionHeader}>
          <h2 className={styles.sectionTitle}>
            {t('Transaktionen')}
            {(selectedMandateId || selectedUserId) && (
              <span style={{ fontWeight: 'normal', fontSize: '14px', marginLeft: '8px' }}>
                {t('({count} gefiltert)', { count: filteredTransactionCount })}
              </span>
            )}
          </h2>
        </div>
        {loading && transactions.length === 0 ? (
          <div className={styles.loadingPlaceholder}>{t('Transaktionen laden')}</div>
        ) : transactions.length === 0 ? (
          <div className={styles.noData}>{t('Keine Transaktionen vorhanden')}</div>
        ) : (
          <>
            <UserTransactionTable
              transactions={transactions}
              selectedMandateId={selectedMandateId}
              selectedUserId={selectedUserId}
            />
            
            {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 BillingUserView;
