'use client';

import Link from 'next/link';
import { useParams, useSearchParams } from 'next/navigation';
import { useEffect, useMemo, useState } from 'react';
import { getEvalCaseHistory, type EvalCaseHistoryItem } from '@/lib/admin-eval-runs';
import { useTranslation } from '@/lib/i18n';

function formatDateTime(value: string | null | undefined): string {
  if (!value) return '—';
  const date = new Date(value);
  return Number.isNaN(date.getTime()) ? value : date.toLocaleString();
}

function prettyLabel(value: string): string {
  if (!value) return '—';
  return value.replace(/_/g, ' ');
}

function StatusBadge({ value }: { value: string }) {
  const normalized = value.toLowerCase();
  let background = '#eef2ff';
  let color = '#4338ca';
  if (normalized === 'completed' || normalized === 'pass') {
    background = '#dcfce7';
    color = '#166534';
  } else if (normalized === 'running' || normalized === 'pending') {
    background = '#dbeafe';
    color = '#1d4ed8';
  } else if (normalized === 'failed' || normalized === 'invalid') {
    background = '#fee2e2';
    color = '#b91c1c';
  } else if (normalized === 'skipped') {
    background = '#fef3c7';
    color = '#92400e';
  }
  return (
    <span
      style={{
        display: 'inline-flex',
        alignItems: 'center',
        padding: '4px 10px',
        borderRadius: 999,
        background,
        color,
        fontSize: 12,
        fontWeight: 700,
        textTransform: 'capitalize',
      }}
    >
      {prettyLabel(value)}
    </span>
  );
}

function caseVerdict(item: EvalCaseHistoryItem): string {
  return item.judgment?.judgment_verdict || item.case_run.execution_status;
}

export default function AdminEvalCaseHistoryPage() {
  const { t } = useTranslation();
  const params = useParams<{ caseId: string }>();
  const searchParams = useSearchParams();
  const caseId = typeof params.caseId === 'string' ? params.caseId : '';
  const currentQuery = searchParams.toString();
  const runsHref = currentQuery ? `/admin/evaluations/runs?${currentQuery}` : '/admin/evaluations/runs';
  const runDetailHref = (runId: string) =>
    `/admin/evaluations/runs/${encodeURIComponent(runId)}${currentQuery ? `?${currentQuery}` : ''}`;
  const [history, setHistory] = useState<EvalCaseHistoryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    let cancelled = false;
    async function load() {
      if (!caseId) return;
      setLoading(true);
      setError('');
      try {
        const items = await getEvalCaseHistory(caseId, 30);
        if (!cancelled) setHistory(items);
      } catch (err) {
        if (!cancelled) setError(err instanceof Error ? err.message : t('adminEvalCaseHistory.loadError'));
      } finally {
        if (!cancelled) setLoading(false);
      }
    }
    load();
    return () => {
      cancelled = true;
    };
  }, [caseId, t]);

  const summary = useMemo(() => {
    let pass = 0;
    let fail = 0;
    let invalid = 0;
    for (const item of history) {
      const verdict = caseVerdict(item);
      if (verdict === 'pass') pass += 1;
      else if (verdict === 'invalid') invalid += 1;
      else fail += 1;
    }
    return { pass, fail, invalid };
  }, [history]);

  if (loading) {
    return <div style={{ paddingTop: 8, fontSize: 14, color: '#6b7280' }}>{t('adminEvalCaseHistory.loading')}</div>;
  }

  return (
    <div style={{ paddingTop: 8 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16, alignItems: 'flex-start', marginBottom: 24 }}>
        <div>
          <div style={{ marginBottom: 8 }}>
            <Link href={runsHref} style={{ fontSize: 13, fontWeight: 600, color: '#5c5fbc', textDecoration: 'none' }}>
              {t('adminEvalCaseHistory.backToRuns')}
            </Link>
          </div>
          <h1 style={{ margin: 0, fontSize: 24, fontWeight: 700, color: '#1a1a2e' }}>{caseId}</h1>
          <p style={{ margin: '8px 0 0', fontSize: 14, lineHeight: 1.6, color: '#6b7280' }}>
            {t('adminEvalCaseHistory.subtitle')}
          </p>
        </div>
      </div>

      {error && (
        <div
          style={{
            marginBottom: 18,
            padding: '14px 16px',
            borderRadius: 12,
            background: '#fef2f2',
            border: '1px solid #fecaca',
            color: '#991b1b',
            fontSize: 13,
          }}
        >
          {error}
        </div>
      )}

      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
          gap: 12,
          marginBottom: 18,
        }}
      >
        {[
          [t('adminEvalCaseHistory.kpiRuns'), String(history.length)],
          [t('adminEvalCaseHistory.kpiPasses'), String(summary.pass)],
          [t('adminEvalCaseHistory.kpiFailures'), String(summary.fail)],
          [t('adminEvalCaseHistory.kpiInvalid'), String(summary.invalid)],
        ].map(([label, value]) => (
          <div key={label} style={{ background: '#fff', borderRadius: 14, border: '1px solid #ececf4', boxShadow: '0 2px 10px rgba(92,95,188,0.06)', padding: '16px 18px' }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: '#9ca3af', letterSpacing: '0.06em', textTransform: 'uppercase' }}>{label}</div>
            <div style={{ marginTop: 8, fontSize: 24, fontWeight: 700, color: '#1f2937' }}>{value}</div>
          </div>
        ))}
      </div>

      <div
        style={{
          background: '#fff',
          borderRadius: 14,
          border: '1px solid #ececf4',
          boxShadow: '0 2px 10px rgba(92,95,188,0.06)',
          overflow: 'hidden',
        }}
      >
        <div style={{ padding: '16px 18px', borderBottom: '1px solid #eef2f7' }}>
          <div style={{ fontSize: 15, fontWeight: 700, color: '#1f2937' }}>{t('adminEvalCaseHistory.tableTitle')}</div>
          <div style={{ marginTop: 4, fontSize: 12, color: '#6b7280' }}>{t('adminEvalCaseHistory.tableSubtitle', { count: history.length })}</div>
        </div>

        {history.length === 0 ? (
          <div style={{ padding: 28, color: '#6b7280', fontSize: 14 }}>{t('adminEvalCaseHistory.empty')}</div>
        ) : (
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 1120 }}>
              <thead>
                <tr style={{ background: '#f8fafc' }}>
                  {[
                    t('adminEvalCaseHistory.colRun'),
                    t('adminEvalCaseHistory.colSuite'),
                    t('adminEvalCaseHistory.colTriggerMode'),
                    t('adminEvalCaseHistory.colExecutionStatus'),
                    t('adminEvalCaseHistory.colVerdict'),
                    t('adminEvalCaseHistory.colScore'),
                    t('adminEvalCaseHistory.colFailureCode'),
                    t('adminEvalCaseHistory.colStartedAt'),
                    t('adminEvalCaseHistory.colFinishedAt'),
                  ].map((label) => (
                    <th key={label} style={{ padding: '12px 14px', fontSize: 12, textAlign: 'left', color: '#6b7280', borderBottom: '1px solid #e5e7eb' }}>
                      {label}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {history.map((item) => (
                  <tr key={item.case_run.id}>
                    <td style={{ padding: '12px 14px', borderBottom: '1px solid #f1f5f9', fontSize: 13 }}>
                      <Link
                        href={runDetailHref(item.run.id)}
                        style={{ color: '#4338ca', textDecoration: 'none', fontWeight: 600 }}
                      >
                        {item.run.id}
                      </Link>
                    </td>
                    <td style={{ padding: '12px 14px', borderBottom: '1px solid #f1f5f9', fontSize: 13 }}>{item.run.suite_id}</td>
                    <td style={{ padding: '12px 14px', borderBottom: '1px solid #f1f5f9', fontSize: 13 }}>{prettyLabel(item.run.trigger_mode)}</td>
                    <td style={{ padding: '12px 14px', borderBottom: '1px solid #f1f5f9', fontSize: 13 }}><StatusBadge value={item.case_run.execution_status} /></td>
                    <td style={{ padding: '12px 14px', borderBottom: '1px solid #f1f5f9', fontSize: 13 }}><StatusBadge value={caseVerdict(item)} /></td>
                    <td style={{ padding: '12px 14px', borderBottom: '1px solid #f1f5f9', fontSize: 13 }}>{item.judgment?.score ?? '—'}</td>
                    <td style={{ padding: '12px 14px', borderBottom: '1px solid #f1f5f9', fontSize: 13 }}>{item.judgment?.primary_failure_code || '—'}</td>
                    <td style={{ padding: '12px 14px', borderBottom: '1px solid #f1f5f9', fontSize: 13 }}>{formatDateTime(item.case_run.started_at)}</td>
                    <td style={{ padding: '12px 14px', borderBottom: '1px solid #f1f5f9', fontSize: 13 }}>{formatDateTime(item.case_run.finished_at)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}
