// V2 per-item detail page — ported from EvalReportItemPage.tsx
import { Page, View, Text } from '@react-pdf/renderer';
import { styles, colors } from '../styles.js';
import type { EvaluationResult, CriterionScore, RubricRuleScore } from './types.js';

interface EvalReportItemPageProps {
  result: EvaluationResult;
  itemNumber: number;
  totalItems: number;
}

const severityColors: Record<string, string> = {
  High: '#3a4389',
  high: '#3a4389',
  Medium: '#4752a3',
  medium: '#4752a3',
  Low: '#7c85c0',
  low: '#7c85c0',
};

function parseTurnsForExcerpt(text: string, maxTurns: number = 3): Array<{ role: string; content: string }> {
  const turns: Array<{ role: string; content: string }> = [];
  const lines = text.split('\n');
  let currentRole: string | null = null;
  let currentContent: string[] = [];

  for (const line of lines) {
    if (line.startsWith('User:')) {
      if (currentRole) turns.push({ role: currentRole, content: currentContent.join('\n').trim() });
      currentRole = 'User';
      currentContent = [line.slice(5).trim()];
    } else if (line.startsWith('Agent:')) {
      if (currentRole) turns.push({ role: currentRole, content: currentContent.join('\n').trim() });
      currentRole = 'Agent';
      currentContent = [line.slice(6).trim()];
    } else if (currentRole) {
      currentContent.push(line);
    }
  }
  if (currentRole) turns.push({ role: currentRole, content: currentContent.join('\n').trim() });
  return turns.slice(0, maxTurns);
}

function CriterionScoreRow({ criterion }: { criterion: CriterionScore }) {
  return (
    <View style={{ flexDirection: 'row', marginBottom: 4, paddingVertical: 3, paddingHorizontal: 6, backgroundColor: criterion.passed ? '#f0fdf4' : '#fef2f2', borderRadius: 3 }}>
      <Text style={{ fontSize: 7, fontWeight: 700, color: criterion.passed ? colors.success : colors.error, width: 12 }}>
        {criterion.passed ? 'P' : 'F'}
      </Text>
      <View style={{ flex: 1 }}>
        <Text style={{ fontSize: 6, fontWeight: 600, color: colors.eggplant, marginBottom: 1 }}>
          {criterion.criterion}
        </Text>
        {criterion.reasoning && (
          <Text style={{ fontSize: 5.5, color: colors.muted, lineHeight: 1.3 }}>
            {criterion.reasoning.slice(0, 250)}{criterion.reasoning.length > 250 ? '...' : ''}
          </Text>
        )}
      </View>
      <Text style={{ fontSize: 6, fontWeight: 600, color: criterion.passed ? colors.success : colors.error, width: 30, textAlign: 'right' }}>
        {Math.round(criterion.score * 100)}%
      </Text>
    </View>
  );
}

function RubricScoreRow({ rule }: { rule: RubricRuleScore }) {
  const sevColor = severityColors[rule.severity] || colors.muted;
  return (
    <View style={{ flexDirection: 'row', marginBottom: 4, paddingVertical: 3, paddingHorizontal: 6, backgroundColor: rule.passed ? '#f0fdf4' : '#fef2f2', borderRadius: 3 }}>
      <Text style={{ fontSize: 7, fontWeight: 700, color: rule.passed ? colors.success : colors.error, width: 12 }}>
        {rule.passed ? 'P' : 'F'}
      </Text>
      <View style={{ flex: 1 }}>
        <View style={{ flexDirection: 'row', alignItems: 'center', gap: 4, marginBottom: 1 }}>
          <Text style={{ fontSize: 6, fontWeight: 600, color: colors.eggplant }}>
            {rule.rule_name}
          </Text>
          <View style={{ backgroundColor: `${sevColor}20`, paddingHorizontal: 4, paddingVertical: 1, borderRadius: 2 }}>
            <Text style={{ fontSize: 5, fontWeight: 600, color: sevColor, textTransform: 'uppercase' }}>
              {rule.severity}
            </Text>
          </View>
        </View>
        {rule.reasoning && (
          <Text style={{ fontSize: 5.5, color: colors.muted, lineHeight: 1.3 }}>
            {rule.reasoning.slice(0, 250)}{rule.reasoning.length > 250 ? '...' : ''}
          </Text>
        )}
      </View>
      <Text style={{ fontSize: 6, fontWeight: 600, color: rule.passed ? colors.success : colors.error, width: 30, textAlign: 'right' }}>
        {Math.round(rule.score * 100)}%
      </Text>
    </View>
  );
}

export function EvalReportItemPage({ result, itemNumber, totalItems }: EvalReportItemPageProps) {
  const itemName = result.item_name || result.input.message || `Test Item ${itemNumber}`;
  const itemType = result.item_type || 'single_turn';
  const criteriaScores = result.criteria_scores || [];
  const rubricScores = result.rubric_scores || [];
  const overallPassed = result.passed ?? (result.criteria_passed !== false && result.rubric_passed !== false);

  const criteriaPassed = criteriaScores.filter(c => c.passed).length;
  const rubricPassed = rubricScores.filter(r => r.passed).length;

  const transcript = (itemType === 'scenario' || itemType === 'transcript')
    ? ((result.output.transcript as string | undefined) || result.output.response || '')
    : '';
  const transcriptTurns = (itemType === 'scenario' || itemType === 'transcript') ? parseTurnsForExcerpt(transcript) : [];

  return (
    <Page size="A4" style={[styles.page, { padding: 24 }]} wrap>
      {/* Header */}
      <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10, paddingBottom: 6, borderBottomWidth: 1, borderBottomColor: colors.border }} fixed>
        <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8 }}>
          <Text style={{ fontSize: 11, fontWeight: 600, color: colors.iris }}>
            Item {itemNumber} of {totalItems}
          </Text>
          <View style={{
            backgroundColor: itemType === 'scenario' ? `${colors.iris}20`
              : itemType === 'transcript' ? '#10b98120'
              : `${colors.muted}20`,
            paddingHorizontal: 6,
            paddingVertical: 2,
            borderRadius: 3,
          }}>
            <Text style={{ fontSize: 7, fontWeight: 600, color: itemType === 'scenario' ? colors.iris : itemType === 'transcript' ? '#059669' : colors.muted }}>
              {itemType === 'single_turn' ? 'SINGLE TURN' : itemType === 'transcript' ? 'TRANSCRIPT' : 'SCENARIO'}
            </Text>
          </View>
        </View>
        <View style={{
          backgroundColor: overallPassed ? '#dcfce7' : '#fee2e2',
          paddingHorizontal: 8,
          paddingVertical: 3,
          borderRadius: 3,
        }}>
          <Text style={{ fontSize: 10, fontWeight: 700, color: overallPassed ? colors.success : colors.error }}>
            {overallPassed ? 'PASSED' : 'FAILED'}
          </Text>
        </View>
      </View>

      {/* Item Name */}
      <View style={{ marginBottom: 8 }} wrap={false}>
        <Text style={{ fontSize: 6, fontWeight: 700, color: colors.eggplant, marginBottom: 3, textTransform: 'uppercase', letterSpacing: 0.5 }}>
          Test Item
        </Text>
        <View style={{ backgroundColor: colors.background, padding: 6, borderRadius: 3 }}>
          <Text style={{ fontSize: 7, color: colors.eggplant, lineHeight: 1.4 }}>{itemName}</Text>
        </View>
      </View>

      {/* Transcript excerpt for scenarios */}
      {transcriptTurns.length > 0 && (
        <View style={{ marginBottom: 8 }}>
          <Text style={{ fontSize: 6, fontWeight: 700, color: colors.eggplant, marginBottom: 3, textTransform: 'uppercase', letterSpacing: 0.5 }}>
            Conversation Excerpt ({transcriptTurns.length} turn{transcriptTurns.length > 1 ? 's' : ''})
          </Text>
          <View style={{ backgroundColor: colors.background, padding: 6, borderRadius: 3 }}>
            {transcriptTurns.map((turn, i) => (
              <View key={i} style={{ marginBottom: i < transcriptTurns.length - 1 ? 4 : 0 }}>
                <Text style={{ fontSize: 5.5, fontWeight: 700, color: turn.role === 'User' ? colors.muted : colors.iris, marginBottom: 1 }}>
                  {turn.role}
                </Text>
                <Text style={{ fontSize: 5.5, color: colors.eggplant, lineHeight: 1.3 }}>
                  {turn.content.slice(0, 200)}{turn.content.length > 200 ? '...' : ''}
                </Text>
              </View>
            ))}
          </View>
        </View>
      )}

      {/* Two-column layout for criteria and rubric scores */}
      <View style={{ flexDirection: 'row', gap: 10 }}>
        {/* Criteria Scores */}
        {criteriaScores.length > 0 && (
          <View style={{ flex: 1 }}>
            <Text style={{ fontSize: 6, fontWeight: 700, color: colors.eggplant, marginBottom: 4, textTransform: 'uppercase', letterSpacing: 0.5 }}>
              Criteria Scores ({criteriaPassed}/{criteriaScores.length} passed)
            </Text>
            {criteriaScores.map((criterion, i) => (
              <CriterionScoreRow key={i} criterion={criterion} />
            ))}
          </View>
        )}

        {/* Rubric Rule Scores */}
        {rubricScores.length > 0 && (
          <View style={{ flex: 1 }}>
            <Text style={{ fontSize: 6, fontWeight: 700, color: colors.eggplant, marginBottom: 4, textTransform: 'uppercase', letterSpacing: 0.5 }}>
              Rubric Scores ({rubricPassed}/{rubricScores.length} passed)
            </Text>
            {rubricScores.map((rule) => (
              <RubricScoreRow key={rule.rule_id} rule={rule} />
            ))}
          </View>
        )}
      </View>

      {/* Footer */}
      <View style={{ flexDirection: 'row', justifyContent: 'space-between', paddingTop: 6, borderTopWidth: 0.5, borderTopColor: colors.border, marginTop: 'auto' }} fixed>
        <Text style={{ fontSize: 6, color: colors.muted }}>Indemn Evaluation Report</Text>
        <Text style={{ fontSize: 6, color: colors.muted }} render={({ pageNumber: pn }) => `Page ${pn}`} />
      </View>
    </Page>
  );
}
