'use client';

import React from 'react';
import { t } from '@/i18n/locales';
import { useApi } from '@/lib/use-api';

/**
 * 券分析仪表盘
 *
 * 券发行/核销/过期统计、品类分布、热销排行、Breakage趋势、二级市场分析
 */

interface CouponAnalyticsData {
  stats: { label: string; value: string; change: string; trend: 'up' | 'down'; color: string }[];
  categoryDistribution: { name: string; count: number; percent: number; color: string }[];
  topCoupons: { rank: number; brand: string; name: string; sales: number; revenue: string; rating: number }[];
  breakageTrend: { month: string; rate: string }[];
  secondaryMarket: { metric: string; value: string; change: string; trend: 'up' | 'down' }[];
}

const loadingBox: React.CSSProperties = {
  display: 'flex', alignItems: 'center', justifyContent: 'center',
  padding: 40, color: 'var(--color-text-tertiary)', font: 'var(--text-body)',
};

export const CouponAnalyticsPage: React.FC = () => {
  const { data, isLoading, error } = useApi<CouponAnalyticsData>('/api/v1/admin/analytics/coupons/stats');

  if (error) return <div style={loadingBox}>Error: {error.message}</div>;
  if (isLoading) return <div style={loadingBox}>Loading...</div>;

  const stats = data?.stats ?? [];
  const categoryDistribution = data?.categoryDistribution ?? [];
  const topCoupons = data?.topCoupons ?? [];
  const breakageTrend = data?.breakageTrend ?? [];
  const secondaryMarket = data?.secondaryMarket ?? [];

  return (
    <div>
      <h1 style={{ font: 'var(--text-h1)', color: 'var(--color-text-primary)', marginBottom: 24 }}>
        {t('ca_title')}
      </h1>

      {/* Stats Grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 16, marginBottom: 24 }}>
        {stats.map(stat => (
          <div key={stat.label} style={{
            background: 'var(--color-surface)',
            borderRadius: 'var(--radius-md)',
            border: '1px solid var(--color-border-light)',
            padding: 20,
          }}>
            <div style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)', marginBottom: 8 }}>
              {stat.label}
            </div>
            <div style={{ font: 'var(--text-h1)', color: stat.color }}>
              {stat.value}
            </div>
            <div style={{
              font: 'var(--text-label-sm)',
              color: stat.trend === 'up' ? 'var(--color-success)' : 'var(--color-error)',
              marginTop: 4,
            }}>
              {stat.change}
            </div>
          </div>
        ))}
      </div>

      {/* Category Distribution + Price Histogram */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 24 }}>
        {/* Category Distribution */}
        <div style={{
          background: 'var(--color-surface)',
          borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)',
          padding: 20,
        }}>
          <div style={{ font: 'var(--text-h3)', marginBottom: 16 }}>{t('ca_category_distribution')}</div>
          {categoryDistribution.map(cat => (
            <div key={cat.name} style={{ marginBottom: 14 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                <span style={{ font: 'var(--text-label-sm)', color: 'var(--color-text-primary)' }}>{cat.name}</span>
                <span style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)' }}>
                  {cat.count.toLocaleString()} ({cat.percent}%)
                </span>
              </div>
              <div style={{
                width: '100%', height: 8,
                background: 'var(--color-gray-100)',
                borderRadius: 4,
                overflow: 'hidden',
              }}>
                <div style={{
                  width: `${cat.percent}%`,
                  height: '100%',
                  background: cat.color,
                  borderRadius: 4,
                }} />
              </div>
            </div>
          ))}
        </div>

        {/* Price Distribution Histogram */}
        <div style={{
          background: 'var(--color-surface)',
          borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)',
          padding: 20,
        }}>
          <div style={{ font: 'var(--text-h3)', marginBottom: 16 }}>{t('ca_face_value_distribution')}</div>
          <div style={{
            height: 260,
            background: 'var(--color-gray-50)',
            borderRadius: 'var(--radius-sm)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'var(--color-text-tertiary)',
          }}>
            Recharts 柱状图 (面值区间: $0-25 / $25-50 / $50-100 / $100-200 / $200+)
          </div>
        </div>
      </div>

      {/* Top 10 Best-Selling Coupons */}
      <div style={{
        background: 'var(--color-surface)',
        borderRadius: 'var(--radius-md)',
        border: '1px solid var(--color-border-light)',
        overflow: 'hidden',
        marginBottom: 24,
      }}>
        <div style={{ padding: '16px 20px', font: 'var(--text-h3)', borderBottom: '1px solid var(--color-border-light)' }}>
          {t('ca_top_selling')}
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr style={{ background: 'var(--color-gray-50)' }}>
              {[t('ca_th_rank'), t('ca_th_brand'), t('ca_th_coupon_name'), t('ca_th_sales'), t('ca_th_revenue'), t('ca_th_rating')].map(h => (
                <th key={h} style={{
                  font: 'var(--text-label-sm)',
                  color: 'var(--color-text-tertiary)',
                  padding: '10px 14px',
                  textAlign: 'left',
                }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {topCoupons.map(row => (
              <tr key={row.rank} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                <td style={{
                  font: 'var(--text-label-sm)',
                  padding: '10px 14px',
                  color: row.rank <= 3 ? 'var(--color-primary)' : 'var(--color-text-tertiary)',
                  fontWeight: row.rank <= 3 ? 700 : 400,
                }}>{row.rank}</td>
                <td style={{ font: 'var(--text-label-sm)', padding: '10px 14px' }}>{row.brand}</td>
                <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px' }}>{row.name}</td>
                <td style={{ font: 'var(--text-body-sm)', padding: '10px 14px' }}>{row.sales.toLocaleString()}</td>
                <td style={{ font: 'var(--text-label-sm)', color: 'var(--color-success)', padding: '10px 14px' }}>{row.revenue}</td>
                <td style={{ padding: '10px 14px' }}>
                  <span style={{
                    padding: '2px 8px',
                    borderRadius: 'var(--radius-full)',
                    background: row.rating >= 4.7 ? 'var(--color-success-light)' : 'var(--color-warning-light)',
                    color: row.rating >= 4.7 ? 'var(--color-success)' : 'var(--color-warning)',
                    font: 'var(--text-caption)',
                  }}>
                    {row.rating}
                  </span>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Breakage Rate Trend + Secondary Market */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {/* Breakage Rate Trend */}
        <div style={{
          background: 'var(--color-surface)',
          borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)',
          padding: 20,
        }}>
          <div style={{ font: 'var(--text-h3)', marginBottom: 16 }}>{t('ca_breakage_trend')}</div>
          <div style={{
            height: 160,
            background: 'var(--color-gray-50)',
            borderRadius: 'var(--radius-sm)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'var(--color-text-tertiary)',
            marginBottom: 16,
          }}>
            Recharts 折线图 (月度 Breakage Rate)
          </div>
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            {breakageTrend.map(item => (
              <div key={item.month} style={{
                padding: '6px 12px',
                background: 'var(--color-gray-50)',
                borderRadius: 'var(--radius-sm)',
                font: 'var(--text-caption)',
                color: 'var(--color-text-secondary)',
              }}>
                {item.month}: <span style={{ color: 'var(--color-primary)', fontWeight: 600 }}>{item.rate}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Secondary Market Analytics */}
        <div style={{
          background: 'var(--color-surface)',
          borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)',
          padding: 20,
        }}>
          <div style={{ font: 'var(--text-h3)', marginBottom: 16 }}>{t('ca_secondary_market')}</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            {secondaryMarket.map(item => (
              <div key={item.metric} style={{
                padding: 12,
                background: 'var(--color-gray-50)',
                borderRadius: 'var(--radius-sm)',
              }}>
                <div style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)', marginBottom: 4 }}>
                  {item.metric}
                </div>
                <div style={{ font: 'var(--text-h3)', color: 'var(--color-text-primary)' }}>
                  {item.value}
                </div>
                <div style={{
                  font: 'var(--text-caption)',
                  color: item.trend === 'up' ? 'var(--color-success)' : 'var(--color-error)',
                  marginTop: 2,
                }}>
                  {item.change}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};
