'use client';

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

/**
 * 用户分析仪表盘
 *
 * 用户增长趋势、KYC分布、地理分布、留存矩阵、活跃分群
 */

interface UserAnalyticsData {
  stats: { label: string; value: string; change: string; trend: 'up' | 'down'; color: string }[];
  kycDistribution: { level: string; count: number; percent: number; color: string }[];
  geoDistribution: { rank: number; region: string; users: string; percent: string }[];
  cohortRetention: { cohort: string; week0: string; week1: string; week2: string; week3: string; week4: string }[];
  segments: { name: string; count: string; percent: number; color: string }[];
}

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

export const UserAnalyticsPage: React.FC = () => {
  const [period, setPeriod] = useState('30D');
  const { data, isLoading, error } = useApi<UserAnalyticsData>('/api/v1/admin/analytics/users/stats', { params: { period } });

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

  const stats = data?.stats ?? [];
  const kycDistribution = data?.kycDistribution ?? [];
  const geoDistribution = data?.geoDistribution ?? [];
  const cohortRetention = data?.cohortRetention ?? [];
  const userSegments = data?.segments ?? [];

  return (
    <div>
      <h1 style={{ font: 'var(--text-h1)', color: 'var(--color-text-primary)', marginBottom: 24 }}>
        {t('ua_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>

      {/* User Growth Chart */}
      <div style={{
        background: 'var(--color-surface)',
        borderRadius: 'var(--radius-md)',
        border: '1px solid var(--color-border-light)',
        padding: 20,
        marginBottom: 24,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
          <span style={{ font: 'var(--text-h3)' }}>{t('ua_growth_trend')}</span>
          <div style={{ display: 'flex', gap: 8 }}>
            {['7D', '30D', '90D', '1Y'].map(p => (
              <button key={p} onClick={() => setPeriod(p)} style={{
                padding: '4px 10px',
                border: '1px solid var(--color-border)',
                borderRadius: 'var(--radius-full)',
                background: p === period ? 'var(--color-primary)' : 'none',
                color: p === period ? 'white' : 'var(--color-text-tertiary)',
                cursor: 'pointer',
                font: 'var(--text-caption)',
              }}>{p}</button>
            ))}
          </div>
        </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 面积图 (用户增长 / DAU / MAU)
        </div>
      </div>

      {/* KYC Distribution + Geographic Distribution */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 24 }}>
        {/* KYC 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('ua_kyc_distribution')}</div>
          {kycDistribution.map(item => (
            <div key={item.level} style={{ marginBottom: 16 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
                <span style={{ font: 'var(--text-label-sm)', color: 'var(--color-text-primary)' }}>{item.level}</span>
                <span style={{ font: 'var(--text-body-sm)', color: 'var(--color-text-tertiary)' }}>
                  {item.count.toLocaleString()} ({item.percent}%)
                </span>
              </div>
              <div style={{
                width: '100%', height: 8,
                background: 'var(--color-gray-100)',
                borderRadius: 4,
                overflow: 'hidden',
              }}>
                <div style={{
                  width: `${item.percent}%`,
                  height: '100%',
                  background: item.color,
                  borderRadius: 4,
                }} />
              </div>
            </div>
          ))}
        </div>

        {/* Geographic Distribution */}
        <div style={{
          background: 'var(--color-surface)',
          borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)',
          overflow: 'hidden',
        }}>
          <div style={{ padding: '16px 20px', font: 'var(--text-h3)', borderBottom: '1px solid var(--color-border-light)' }}>
            {t('ua_geo_distribution')}
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ background: 'var(--color-gray-50)' }}>
                {[t('ua_th_rank'), t('ua_th_region'), t('ua_th_users'), t('ua_th_percent')].map(h => (
                  <th key={h} style={{
                    font: 'var(--text-label-sm)',
                    color: 'var(--color-text-tertiary)',
                    padding: '8px 14px',
                    textAlign: 'left',
                  }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {geoDistribution.map(row => (
                <tr key={row.rank} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                  <td style={{ font: 'var(--text-label-sm)', color: 'var(--color-text-tertiary)', padding: '8px 14px' }}>{row.rank}</td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '8px 14px' }}>{row.region}</td>
                  <td style={{ font: 'var(--text-body-sm)', padding: '8px 14px' }}>{row.users}</td>
                  <td style={{ font: 'var(--text-body-sm)', color: 'var(--color-primary)', padding: '8px 14px' }}>{row.percent}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Cohort Retention Matrix + User Segments */}
      <div style={{ display: 'grid', gridTemplateColumns: '3fr 2fr', gap: 16 }}>
        {/* Cohort Retention Matrix */}
        <div style={{
          background: 'var(--color-surface)',
          borderRadius: 'var(--radius-md)',
          border: '1px solid var(--color-border-light)',
          overflow: 'hidden',
        }}>
          <div style={{ padding: '16px 20px', font: 'var(--text-h3)', borderBottom: '1px solid var(--color-border-light)' }}>
            {t('ua_retention_matrix')}
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ background: 'var(--color-gray-50)' }}>
                {[t('ua_th_cohort'), 'Week 0', 'Week 1', 'Week 2', 'Week 3', 'Week 4'].map(h => (
                  <th key={h} style={{
                    font: 'var(--text-label-sm)',
                    color: 'var(--color-text-tertiary)',
                    padding: '8px 12px',
                    textAlign: 'left',
                  }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {cohortRetention.map(row => (
                <tr key={row.cohort} style={{ borderBottom: '1px solid var(--color-border-light)' }}>
                  <td style={{ font: 'var(--text-body-sm)', padding: '8px 12px', whiteSpace: 'nowrap' }}>{row.cohort}</td>
                  {[row.week0, row.week1, row.week2, row.week3, row.week4].map((val, i) => {
                    const numVal = parseInt(val);
                    const bgOpacity = !isNaN(numVal) ? Math.max(0.05, numVal / 100 * 0.4) : 0;
                    return (
                      <td key={i} style={{
                        font: 'var(--text-label-sm)',
                        padding: '8px 12px',
                        textAlign: 'center',
                        color: val === '-' ? 'var(--color-text-tertiary)' : 'var(--color-primary)',
                        background: val !== '-' ? `rgba(108, 92, 231, ${bgOpacity})` : 'transparent',
                      }}>
                        {val}
                      </td>
                    );
                  })}
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Active User Segments */}
        <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('ua_user_segments')}</div>
          {userSegments.map(seg => (
            <div key={seg.name} style={{
              display: 'flex',
              alignItems: 'center',
              padding: '12px 0',
              borderBottom: '1px solid var(--color-border-light)',
            }}>
              <span style={{
                width: 10, height: 10,
                borderRadius: '50%',
                background: seg.color,
                marginRight: 10,
                flexShrink: 0,
              }} />
              <div style={{ flex: 1 }}>
                <div style={{ font: 'var(--text-label-sm)', color: 'var(--color-text-primary)' }}>{seg.name}</div>
                <div style={{ font: 'var(--text-caption)', color: 'var(--color-text-tertiary)' }}>{seg.count} {t('ua_unit_people')}</div>
              </div>
              <div style={{ textAlign: 'right' }}>
                <div style={{ font: 'var(--text-h3)', color: seg.color }}>{seg.percent}%</div>
              </div>
            </div>
          ))}
          <div style={{
            marginTop: 16,
            height: 160,
            background: 'var(--color-gray-50)',
            borderRadius: 'var(--radius-sm)',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'var(--color-text-tertiary)',
          }}>
            Recharts 环形图 (用户分群占比)
          </div>
        </div>
      </div>
    </div>
  );
};
