'use client';

import { useTranslation } from '@/lib/i18n';
import {
  getOverviewKPIs,
  getDailyActiveUsers,
  getWorkspaceGrowth,
  getMessageVolume,
  getSkillUsageTrend,
  getSkillStats,
  getVisitFrequency,
  getSessionDuration,
  getSourceTypeBreakdown,
  getUserSegments,
  getFeatureAdoption,
  getRetentionCohort,
  getPeakHoursHeatmap,
  getTopWorkspaces,
} from './mockData';
import {
  AreaChart,
  BarChart,
  DonutChart,
  Heatmap,
  HorizontalBarChart,
  SectionCard,
  SkillBars,
  Sparkline,
} from './charts';

// Simple sparkline seed data for KPI cards
const SPARKLINE_SEEDS: number[][] = [
  [85, 88, 92, 90, 95, 102, 108, 112, 118, 124, 128],
  [32, 35, 34, 38, 40, 39, 42, 44, 43, 46, 47],
  [800, 850, 870, 920, 980, 1020, 1050, 1120, 1150, 1200, 1247],
  [22, 20, 19, 21, 18, 19, 17, 18, 19, 18, 18],
  [5200, 5800, 6100, 6400, 6800, 7200, 7500, 7800, 8000, 8200, 8432],
  [320, 380, 410, 440, 480, 500, 520, 560, 590, 610, 634],
];

export default function AnalyticsDashboard() {
  const { t } = useTranslation();

  const kpis = getOverviewKPIs();
  const dauData = getDailyActiveUsers();
  const workspaceGrowth = getWorkspaceGrowth();
  const messageVolume = getMessageVolume();
  const skillTrend = getSkillUsageTrend();
  const skills = getSkillStats();
  const visitFreq = getVisitFrequency();
  const sessionDur = getSessionDuration();
  const sourceTypes = getSourceTypeBreakdown();
  const userSegments = getUserSegments();
  const featureAdopt = getFeatureAdoption();
  const retention = getRetentionCohort();
  const heatmap = getPeakHoursHeatmap();
  const topWorkspaces = getTopWorkspaces();

  return (
    <div style={{ fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif' }}>
      {/* Page title */}
      <div style={{ marginBottom: 20 }}>
        <h2 style={{ fontSize: 22, fontWeight: 700, color: '#1a1a2e', margin: 0 }}>
          {t('adminAnalytics.title')}
        </h2>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 6, flexWrap: 'wrap' }}>
          <p style={{ fontSize: 13, color: '#9ca3af', margin: 0 }}>
            {t('adminAnalytics.lastUpdated', { date: t('adminAnalytics.lastUpdatedDate') })}
          </p>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 5,
            padding: '2px 9px', background: '#f0fdf4', borderRadius: 20,
            fontSize: 11, color: '#16a34a', fontWeight: 500,
          }}>
            <span style={{ width: 6, height: 6, borderRadius: '50%', background: '#16a34a', display: 'inline-block' }} />
            {t('adminAnalytics.allOperational')}
          </div>
        </div>
      </div>

      {/* ─── WIP Notice ─── */}
      <div style={{
        background: '#fffbeb',
        border: '1px solid #fde68a',
        borderRadius: '10px',
        padding: '14px 18px',
        marginBottom: '16px',
        display: 'flex',
        alignItems: 'flex-start',
        gap: '12px',
      }}>
        <span style={{ fontSize: '20px', flexShrink: 0, lineHeight: 1.4 }}>🚧</span>
        <div>
          <div style={{ fontSize: '14px', fontWeight: 600, color: '#92400e', marginBottom: '4px' }}>
            {t('adminAnalytics.wipTitle')}
          </div>
          <div style={{ fontSize: '13px', color: '#b45309', lineHeight: 1.6 }}>
            {t('adminAnalytics.wipBody')}
          </div>
        </div>
      </div>

      {/* ── KPI Cards ──────────────────────────────────────────────── */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))',
        gap: 12,
        marginBottom: 16,
      }}>
        {kpis.map((kpi, i) => (
          <div key={i} style={{
            background: '#fff',
            borderRadius: 12,
            border: '1px solid #f0f0f5',
            boxShadow: '0 1px 3px rgba(0,0,0,0.04)',
            padding: '16px 18px 12px',
            display: 'flex',
            flexDirection: 'column',
            gap: 6,
          }}>
            <span style={{ fontSize: 10, color: '#9ca3af', fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.5 }}>
              {kpi.label}
            </span>
            <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 24, fontWeight: 700, color: '#1f2937', lineHeight: 1 }}>
                {kpi.value}
              </span>
              <Sparkline data={SPARKLINE_SEEDS[i] || SPARKLINE_SEEDS[0]} color={kpi.change >= 0 ? '#5c5fbc' : '#ef4444'} />
            </div>
            <span style={{ fontSize: 11, fontWeight: 600, color: kpi.change >= 0 ? '#10b981' : '#ef4444' }}>
              {kpi.change >= 0 ? '↑' : '↓'} {t('adminAnalytics.vsLastWeek', { change: Math.abs(kpi.change) })}
            </span>
          </div>
        ))}
      </div>


      {/* ── Row 1: DAU + Workspace Growth ──────────────────────────── */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
        <SectionCard title={t('adminAnalytics.dau')} subtitle={t('adminAnalytics.dauSubtitle')}>
          <AreaChart data={dauData} color="#5c5fbc" height={200} />
        </SectionCard>
        <SectionCard title={t('adminAnalytics.workspaceGrowth')} subtitle={t('adminAnalytics.workspaceGrowthSubtitle')}>
          <AreaChart data={workspaceGrowth} color="#6366f1" height={200} />
        </SectionCard>
      </div>

      {/* ── Row 2: Skill Invocations ───────────────────────────── */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: 14, marginBottom: 14 }}>
        <SectionCard title={t('adminAnalytics.skillUsage')} subtitle={t('adminAnalytics.skillUsageSubtitle')}>
          <SkillBars skills={skills} />
        </SectionCard>
      </div>

      {/* ── Row 3: Peak Hours + Source Types ────────────────────── */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 0.7fr', gap: 14, marginBottom: 14 }}>
        <SectionCard title={t('adminAnalytics.peakHours')} subtitle={t('adminAnalytics.peakHoursSubtitle')}>
          <Heatmap data={heatmap} />
        </SectionCard>
        <SectionCard title={t('adminAnalytics.sourceTypes')} subtitle={t('adminAnalytics.sourceTypesSubtitle')}>
          <DonutChart data={sourceTypes} size={160} />
        </SectionCard>
      </div>

      {/* ── Row 4: Feature Adoption + User Segments ────────────── */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
        <SectionCard title={t('adminAnalytics.featureAdoption')} subtitle={t('adminAnalytics.featureAdoptionSubtitle')}>
          <HorizontalBarChart data={featureAdopt} />
        </SectionCard>
        <SectionCard title={t('adminAnalytics.userSegments')} subtitle={t('adminAnalytics.userSegmentsSubtitle')}>
          <DonutChart data={userSegments} size={150} />
        </SectionCard>
      </div>

      {/* ── Row 5: Message Volume + Skill Trend ────────────────── */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
        <SectionCard title={t('adminAnalytics.messageVolume')} subtitle={t('adminAnalytics.messageVolumeSubtitle')}>
          <AreaChart data={messageVolume} color="#10b981" height={180} />
        </SectionCard>
        <SectionCard title={t('adminAnalytics.skillTrend')} subtitle={t('adminAnalytics.skillTrendSubtitle')}>
          <AreaChart data={skillTrend} color="#8b5cf6" height={180} />
        </SectionCard>
      </div>

      {/* ── Row 6: Session Duration + Retention ────────────────── */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 14 }}>
        <SectionCard title={t('adminAnalytics.sessionDuration')} subtitle={t('adminAnalytics.sessionDurationSubtitle')}>
          <BarChart data={sessionDur} height={180} />
        </SectionCard>
        <SectionCard title={t('adminAnalytics.retention')} subtitle={t('adminAnalytics.retentionSubtitle')}>
          <BarChart data={retention} height={180} />
        </SectionCard>
      </div>

      {/* ── Row 7: Visit Frequency + Workspaces per User ─────── */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginBottom: 20 }}>
        <SectionCard title={t('adminAnalytics.visitFrequency')} subtitle={t('adminAnalytics.visitFrequencySubtitle')}>
          <BarChart data={visitFreq} height={180} />
        </SectionCard>
        <SectionCard title={t('adminAnalytics.workspacesPerUser')} subtitle={t('adminAnalytics.workspacesPerUserSubtitle')}>
          <BarChart
            data={[
              { label: '1', value: 18, color: '#5c5fbc' },
              { label: '2', value: 12, color: '#6366f1' },
              { label: '3', value: 8, color: '#818cf8' },
              { label: '4', value: 5, color: '#a5b4fc' },
              { label: '5+', value: 4, color: '#c4b5fd' },
            ]}
            height={180}
          />
        </SectionCard>
      </div>

      {/* ── Top Workspaces Table ───────────────────────────────── */}
      <SectionCard title={t('adminAnalytics.topWorkspaces')} subtitle={t('adminAnalytics.topWorkspacesSubtitle')}>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
            <thead>
              <tr style={{ borderBottom: '2px solid #f0f0f5' }}>
                {[
                  t('adminAnalytics.colWorkspace'),
                  t('adminAnalytics.colOwner'),
                  t('adminAnalytics.colMessages'),
                  t('adminAnalytics.colSources'),
                  t('adminAnalytics.colLastActive'),
                ].map(h => (
                  <th key={h} style={{
                    textAlign: 'left', padding: '10px 12px',
                    color: '#6b7280', fontWeight: 600, fontSize: 11,
                    textTransform: 'uppercase', letterSpacing: 0.5,
                  }}>
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {topWorkspaces.map((ws, i) => (
                <tr
                  key={i}
                  style={{ borderBottom: '1px solid #f5f5f5', transition: 'background 0.15s' }}
                  onMouseEnter={e => (e.currentTarget.style.background = '#fafaff')}
                  onMouseLeave={e => (e.currentTarget.style.background = 'transparent')}
                >
                  <td style={{ padding: '10px 12px', fontWeight: 500, color: '#1f2937' }}>{ws.name}</td>
                  <td style={{ padding: '10px 12px', color: '#6b7280' }}>{ws.owner}</td>
                  <td style={{ padding: '10px 12px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div style={{
                        height: 6,
                        width: `${(ws.messages / topWorkspaces[0].messages) * 100}%`,
                        maxWidth: 100, background: '#5c5fbc', borderRadius: 3,
                      }} />
                      <span style={{ color: '#4b5563', fontSize: 12 }}>{ws.messages}</span>
                    </div>
                  </td>
                  <td style={{ padding: '10px 12px', color: '#4b5563' }}>{ws.sources}</td>
                  <td style={{ padding: '10px 12px', color: '#9ca3af', fontSize: 12 }}>{ws.lastActive}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </SectionCard>
    </div>
  );
}
