'use client';

/**
 * Stats Cards Component
 *
 * Displays dashboard statistics in card format for the admin dashboard.
 * Shows total dealers, by tier, and by status.
 */

import React, { useMemo } from 'react';
import styles from './StatsCards.module.css';
import { PLAN_PRICES, type TierName } from '@/lib/plan-features';

// Define tier configuration with proper typing to avoid type assertions
const TIER_CONFIG: ReadonlyArray<{ name: string; key: TierName; color: string }> = [
  { name: 'Starter', key: 'starter', color: '#6b7280' },
  { name: 'Growth', key: 'growth', color: '#3b82f6' },
  { name: 'Enhanced', key: 'enhanced', color: '#8b5cf6' },
  { name: 'Professional', key: 'professional', color: '#f59e0b' },
] as const;

interface Stats {
  totalDealers: number;
  byTier: {
    starter: number;
    growth: number;
    enhanced: number;
    professional: number;
  };
  byTierActive?: {
    starter: number;
    growth: number;
    enhanced: number;
    professional: number;
  };
  byStatus: {
    active: number;
    pending: number;
    suspended: number;
    cancelled: number;
    cancelled_pending?: number;
    payment_failed: number;
  };
}

interface StatsCardsProps {
  stats: Stats;
  isLoading?: boolean;
}

export function StatsCards({ stats, isLoading }: StatsCardsProps) {
  if (isLoading) {
    return (
      <div className={styles.grid}>
        {[...Array(5)].map((_, i) => (
          <div key={i} className={`${styles.card} ${styles.skeleton}`}>
            <div className={styles.skeletonTitle}></div>
            <div className={styles.skeletonValue}></div>
          </div>
        ))}
      </div>
    );
  }

  return (
    <div className={styles.grid}>
      {/* Total Dealers */}
      <div className={`${styles.card} ${styles.primary}`}>
        <h3 className={styles.cardTitle}>Total Dealers</h3>
        <p className={styles.cardValue}>{stats.totalDealers}</p>
      </div>

      {/* Active Dealers */}
      <div className={`${styles.card} ${styles.success}`}>
        <h3 className={styles.cardTitle}>Active</h3>
        <p className={styles.cardValue}>{stats.byStatus.active}</p>
      </div>

      {/* Pending Dealers */}
      <div className={`${styles.card} ${styles.warning}`}>
        <h3 className={styles.cardTitle}>Pending</h3>
        <p className={styles.cardValue}>{stats.byStatus.pending}</p>
      </div>

      {/* Payment Failed */}
      <div className={`${styles.card} ${styles.error}`}>
        <h3 className={styles.cardTitle}>Payment Failed</h3>
        <p className={styles.cardValue}>{stats.byStatus.payment_failed}</p>
      </div>

      {/* Suspended/Cancelled */}
      <div className={`${styles.card} ${styles.neutral}`}>
        <h3 className={styles.cardTitle}>Suspended/Cancelled</h3>
        <p className={styles.cardValue}>
          {stats.byStatus.suspended +
            (stats.byStatus.cancelled_pending ?? 0) +
            stats.byStatus.cancelled}
        </p>
      </div>
    </div>
  );
}

/** Format a number as USD currency (no decimals) */
export function formatCurrency(amount: number): string {
  return new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD',
    minimumFractionDigits: 0,
    maximumFractionDigits: 0,
  }).format(amount);
}

export function TierBreakdown({ stats }: { stats: Stats }) {
  // Memoize revenue calculations to avoid recalculation on every render
  const { tierRevenues, totalMonthly, totalAnnual } = useMemo(() => {
    // Use paying tier counts for revenue calculations (falls back to byTier for cached data)
    const activeTiers = stats.byTierActive ?? stats.byTier;
    const revenues = TIER_CONFIG.map((tier) => {
      const count = stats.byTier[tier.key];
      const activeCount = activeTiers[tier.key];
      const pricing = PLAN_PRICES[tier.key];
      return {
        ...tier,
        count,
        monthlyRevenue: activeCount * pricing.annualMonthly,
        annualRevenue: activeCount * pricing.annual,
      };
    });

    return {
      tierRevenues: revenues,
      totalMonthly: revenues.reduce((sum, t) => sum + t.monthlyRevenue, 0),
      totalAnnual: revenues.reduce((sum, t) => sum + t.annualRevenue, 0),
    };
  }, [stats.byTier, stats.byTierActive]);

  return (
    <div className={styles.tierBreakdown}>
      <div className={styles.sectionHeader}>
        <h3 className={styles.sectionTitle}>By Subscription Tier</h3>
        <div className={styles.revenueTotals}>
          <span className={styles.revenueTotalItem} title="Assumes annual billing for all dealers">
            <span className={styles.revenueTotalLabel}>Monthly</span>
            <span className={styles.revenueTotalValue}>{formatCurrency(totalMonthly)}</span>
          </span>
          <span className={styles.revenueTotalItem} title="Assumes annual billing for all dealers">
            <span className={styles.revenueTotalLabel}>Annual</span>
            <span className={styles.revenueTotalValue}>{formatCurrency(totalAnnual)}</span>
          </span>
        </div>
      </div>
      <div className={styles.tierGrid}>
        {tierRevenues.map((tier) => (
          <div key={tier.key} className={styles.tierCard}>
            <div className={styles.tierLeft}>
              <div className={styles.tierHeader}>
                <div className={styles.tierIndicator} style={{ backgroundColor: tier.color }}></div>
                <span className={styles.tierName}>{tier.name}</span>
              </div>
              <div className={styles.tierInfo}>
                <span className={styles.tierCount}>{tier.count}</span>
              </div>
            </div>
            <div className={styles.tierRevenue}>
              <div className={styles.tierRevenueRow}>
                <span className={styles.tierRevenueLabel}>Monthly</span>
                <span className={styles.tierRevenueValue}>
                  {formatCurrency(tier.monthlyRevenue)}
                </span>
              </div>
              <div className={styles.tierRevenueRow}>
                <span className={styles.tierRevenueLabel}>Annual</span>
                <span className={styles.tierRevenueValue}>
                  {formatCurrency(tier.annualRevenue)}
                </span>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}
