'use client';

import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { fetchWithAuth } from '@/lib/auth';
import { useTranslation } from '@/lib/i18n';

interface StatsSummary {
  total_calls: number;
  by_type: {
    skill: number;
    builtin: number;
  };
  top_skills: Array<{
    name: string;
    count: number;
    avg_duration_ms: number;
    percentage: number;
  }>;
  top_builtin: Array<{
    name: string;
    count: number;
    avg_duration_ms: number;
  }>;
  recent: Array<{
    timestamp: number;
    type: string;
    tool_name: string;
    duration_ms: number | null;
    workspace_id?: string;
  }>;
}

export default function StatsPage() {
  const router = useRouter();
  const { t } = useTranslation();
  const [stats, setStats] = useState<StatsSummary | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const loadStats = async () => {
      try {
        const apiUrl = process.env.NEXT_PUBLIC_API_URL || '';
        const response = await fetchWithAuth(`${apiUrl}/api/stats/summary`);
        if (!response.ok) {
          if (response.status === 401) {
            router.push('/login');
            return;
          }
          throw new Error('Failed to load stats');
        }
        const data = await response.json();
        setStats(data);
      } catch (err) {
        setError(err instanceof Error ? err.message : 'Unknown error');
      } finally {
        setLoading(false);
      }
    };

    loadStats();
  }, [router]);

  const formatTimestamp = (ts: number) => {
    return new Date(ts).toLocaleString();
  };

  const getTypeColor = (type: string) => {
    switch (type) {
      case 'skill':
        return '#5c5fbc';
      case 'builtin':
        return '#1565c0';
      default:
        return '#666';
    }
  };

  if (loading) {
    return (
      <div style={{ paddingTop: '40px', textAlign: 'center', color: '#9ca3af', fontSize: 14 }}>
        {t('adminStats.loading')}
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ paddingTop: '40px', textAlign: 'center', color: '#b91c1c', fontSize: 14 }}>
        {t('adminStats.errorPrefix', { error })}
      </div>
    );
  }

  if (!stats) {
    return null;
  }

  return (
    <div style={{ paddingTop: '8px' }}>
      <div style={{ marginBottom: '28px' }}>
        <h1 style={{ margin: 0, fontSize: 22, fontWeight: 700, color: '#1a1a2e' }}>
          {t('adminStats.title')}
        </h1>
        <p style={{ margin: '6px 0 0', fontSize: 14, color: '#6b7280' }}>
          {t('adminStats.subtitle')}
        </p>
      </div>

      {/* Summary Cards */}
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(250px, 1fr))',
          gap: '1rem',
          marginBottom: '2rem',
        }}
      >
        <div
          style={{
            padding: '1.5rem',
            backgroundColor: '#f5f5f5',
            borderRadius: '8px',
            border: '1px solid #e0e0e0',
          }}
        >
          <div style={{ fontSize: '0.875rem', color: '#666', marginBottom: '0.5rem' }}>
            {t('adminStats.totalCalls')}
          </div>
          <div style={{ fontSize: '2rem', fontWeight: 'bold' }}>
            {stats.total_calls.toLocaleString()}
          </div>
        </div>

        <div
          style={{
            padding: '1.5rem',
            backgroundColor: '#f5f5f5',
            borderRadius: '8px',
            border: '1px solid #e0e0e0',
          }}
        >
          <div style={{ fontSize: '0.875rem', color: '#666', marginBottom: '0.5rem' }}>
            {t('adminStats.skillCalls')}
          </div>
          <div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#5c5fbc' }}>
            {stats.by_type.skill.toLocaleString()}
          </div>
        </div>

        <div
          style={{
            padding: '1.5rem',
            backgroundColor: '#f5f5f5',
            borderRadius: '8px',
            border: '1px solid #e0e0e0',
          }}
        >
          <div style={{ fontSize: '0.875rem', color: '#666', marginBottom: '0.5rem' }}>
            {t('adminStats.builtinCalls')}
          </div>
          <div style={{ fontSize: '2rem', fontWeight: 'bold', color: '#1565c0' }}>
            {stats.by_type.builtin.toLocaleString()}
          </div>
        </div>
      </div>

      {/* Top Skills Table */}
      {stats.top_skills.length > 0 && (
        <div style={{ marginBottom: '2rem' }}>
          <h2 style={{ fontSize: '1.5rem', fontWeight: 'bold', marginBottom: '1rem' }}>
            {t('adminStats.topSkills')}
          </h2>
          <div style={{ overflowX: 'auto', backgroundColor: 'white', borderRadius: '8px', border: '1px solid #e0e0e0' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ backgroundColor: '#f5f5f5', borderBottom: '2px solid #e0e0e0' }}>
                  <th style={{ padding: '1rem', textAlign: 'left', fontWeight: '600' }}>{t('adminStats.colSkillName')}</th>
                  <th style={{ padding: '1rem', textAlign: 'right', fontWeight: '600' }}>{t('adminStats.colCallCount')}</th>
                  <th style={{ padding: '1rem', textAlign: 'right', fontWeight: '600' }}>{t('adminStats.colAvgDuration')}</th>
                  <th style={{ padding: '1rem', textAlign: 'right', fontWeight: '600' }}>{t('adminStats.colPercent')}</th>
                </tr>
              </thead>
              <tbody>
                {stats.top_skills.map((skill, idx) => (
                  <tr key={idx} style={{ borderBottom: '1px solid #e0e0e0' }}>
                    <td style={{ padding: '1rem', color: '#5c5fbc', fontWeight: '500' }}>{skill.name}</td>
                    <td style={{ padding: '1rem', textAlign: 'right' }}>{skill.count}</td>
                    <td style={{ padding: '1rem', textAlign: 'right' }}>{skill.avg_duration_ms}</td>
                    <td style={{ padding: '1rem', textAlign: 'right' }}>{skill.percentage}%</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Top Builtin Tools Table */}
      {stats.top_builtin.length > 0 && (
        <div style={{ marginBottom: '2rem' }}>
          <h2 style={{ fontSize: '1.5rem', fontWeight: 'bold', marginBottom: '1rem' }}>
            {t('adminStats.topBuiltin')}
          </h2>
          <div style={{ overflowX: 'auto', backgroundColor: 'white', borderRadius: '8px', border: '1px solid #e0e0e0' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ backgroundColor: '#f5f5f5', borderBottom: '2px solid #e0e0e0' }}>
                  <th style={{ padding: '1rem', textAlign: 'left', fontWeight: '600' }}>{t('adminStats.colToolName')}</th>
                  <th style={{ padding: '1rem', textAlign: 'right', fontWeight: '600' }}>{t('adminStats.colCount')}</th>
                  <th style={{ padding: '1rem', textAlign: 'right', fontWeight: '600' }}>{t('adminStats.colAvgDuration')}</th>
                </tr>
              </thead>
              <tbody>
                {stats.top_builtin.map((tool, idx) => (
                  <tr key={idx} style={{ borderBottom: '1px solid #e0e0e0' }}>
                    <td style={{ padding: '1rem', color: '#1565c0', fontWeight: '500' }}>{tool.name}</td>
                    <td style={{ padding: '1rem', textAlign: 'right' }}>{tool.count}</td>
                    <td style={{ padding: '1rem', textAlign: 'right' }}>{tool.avg_duration_ms}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}

      {/* Recent Activity Table */}
      {stats.recent.length > 0 && (
        <div style={{ marginBottom: '2rem' }}>
          <h2 style={{ fontSize: '1.5rem', fontWeight: 'bold', marginBottom: '1rem' }}>
            {t('adminStats.recentActivity')}
          </h2>
          <div style={{ overflowX: 'auto', backgroundColor: 'white', borderRadius: '8px', border: '1px solid #e0e0e0' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <thead>
                <tr style={{ backgroundColor: '#f5f5f5', borderBottom: '2px solid #e0e0e0' }}>
                  <th style={{ padding: '1rem', textAlign: 'left', fontWeight: '600' }}>{t('adminStats.colTime')}</th>
                  <th style={{ padding: '1rem', textAlign: 'left', fontWeight: '600' }}>{t('adminStats.colType')}</th>
                  <th style={{ padding: '1rem', textAlign: 'left', fontWeight: '600' }}>{t('adminStats.colToolName')}</th>
                  <th style={{ padding: '1rem', textAlign: 'right', fontWeight: '600' }}>{t('adminStats.colDuration')}</th>
                </tr>
              </thead>
              <tbody>
                {stats.recent.map((activity, idx) => (
                  <tr key={idx} style={{ borderBottom: '1px solid #e0e0e0' }}>
                    <td style={{ padding: '1rem', fontSize: '0.875rem' }}>
                      {formatTimestamp(activity.timestamp)}
                    </td>
                    <td style={{ padding: '1rem' }}>
                      <span
                        style={{
                          padding: '0.25rem 0.5rem',
                          borderRadius: '4px',
                          fontSize: '0.75rem',
                          fontWeight: '500',
                          backgroundColor: getTypeColor(activity.type) + '20',
                          color: getTypeColor(activity.type),
                        }}
                      >
                        {activity.type}
                      </span>
                    </td>
                    <td style={{ padding: '1rem', fontFamily: 'monospace', fontSize: '0.875rem' }}>
                      {activity.tool_name}
                    </td>
                    <td style={{ padding: '1rem', textAlign: 'right' }}>
                      {activity.duration_ms ?? '-'}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
}
