import { StyleSheet, Text, View } from 'react-native';
import { UploadedFileContextItem } from '../../services/askDrAi';
import { colors, spacing } from '../../constants/theme';
import { DocumentDisplayPanel } from './DocumentDisplayPanel';

const STATUS_LABELS: Record<string, string> = {
  ok: 'Content read successfully',
  empty: 'No readable text found',
  image_no_text: 'Image uploaded — text could not be detected',
  missing: 'File not found',
  invalid_path: 'Invalid file path',
  error: 'Could not read file',
};

type Props = {
  file: UploadedFileContextItem;
};

export function UploadedFileAnalysisCard({ file }: Props) {
  const hasDisplay = Array.isArray(file.display?.sections) && (file.display?.sections?.length ?? 0) > 0;
  const statusLabel = STATUS_LABELS[file.status] || file.status || 'Processed';

  return (
    <View style={styles.card}>
      <View style={styles.header}>
        <View style={styles.headerText}>
          <Text style={styles.filename}>{file.filename}</Text>
          <Text style={[styles.status, file.status === 'ok' && styles.statusOk]}>{statusLabel}</Text>
        </View>
        {file.char_count ? (
          <Text style={styles.meta}>{file.char_count} chars</Text>
        ) : null}
      </View>

      {file.message && !hasDisplay ? (
        <Text style={styles.message}>{file.message}</Text>
      ) : null}

      {hasDisplay ? <DocumentDisplayPanel display={file.display} /> : null}

      {!hasDisplay && file.excerpt ? (
        <Text style={styles.fallback}>{file.excerpt}</Text>
      ) : null}
    </View>
  );
}

const styles = StyleSheet.create({
  card: {
    backgroundColor: colors.surface,
    borderColor: colors.border,
    borderRadius: 10,
    borderWidth: 1,
    gap: spacing.sm,
    padding: spacing.md,
  },
  header: {
    flexDirection: 'row',
    gap: spacing.sm,
    justifyContent: 'space-between',
  },
  headerText: {
    flex: 1,
    gap: 2,
  },
  filename: {
    color: colors.text,
    fontSize: 14,
    fontWeight: '600',
  },
  status: {
    color: colors.textMuted,
    fontSize: 12,
  },
  statusOk: {
    color: '#047857',
  },
  meta: {
    backgroundColor: colors.background,
    borderRadius: 999,
    color: colors.textMuted,
    fontSize: 11,
    paddingHorizontal: 8,
    paddingVertical: 3,
  },
  message: {
    color: colors.textMuted,
    fontSize: 13,
    lineHeight: 18,
  },
  fallback: {
    color: colors.textMuted,
    fontSize: 12,
    lineHeight: 17,
  },
});
