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

export type DocumentDisplayFieldRow = { label?: string; value?: string };
export type DocumentDisplayTableRow = {
  test?: string;
  result?: string;
  unit?: string;
  reference?: string;
  flag?: string;
};

export type DocumentDisplaySection = {
  title?: string;
  type?: 'fields' | 'table' | 'paragraphs';
  rows?: DocumentDisplayFieldRow[] | DocumentDisplayTableRow[];
  columns?: { key?: string; label?: string }[];
  paragraphs?: string[];
};

export type DocumentDisplay = {
  summary?: string;
  sections?: DocumentDisplaySection[];
};

type Props = {
  display?: DocumentDisplay | null;
};

function flagStyle(flag: string) {
  const normalized = flag.toLowerCase();
  if (normalized === 'high') return styles.flagHigh;
  if (normalized === 'low') return styles.flagLow;
  return styles.flagNeutral;
}

export function DocumentDisplayPanel({ display }: Props) {
  const sections = display?.sections ?? [];
  if (!display?.summary && sections.length === 0) {
    return null;
  }

  return (
    <View style={styles.panel}>
      {display.summary ? <Text style={styles.summary}>{display.summary}</Text> : null}

      {sections.map((section, sectionIndex) => (
        <View key={`section-${sectionIndex}`} style={styles.section}>
          {section.title ? <Text style={styles.sectionTitle}>{section.title}</Text> : null}

          {section.type === 'fields' && (section.rows as DocumentDisplayFieldRow[] | undefined)?.map((row, rowIndex) => (
            <View key={`field-${sectionIndex}-${rowIndex}`} style={styles.fieldRow}>
              <Text style={styles.fieldLabel}>{row.label}</Text>
              <Text style={styles.fieldValue}>{row.value}</Text>
            </View>
          ))}

          {section.type === 'table' && (section.rows as DocumentDisplayTableRow[] | undefined)?.map((row, rowIndex) => (
            <View key={`table-${sectionIndex}-${rowIndex}`} style={styles.tableRow}>
              <View style={styles.tableMain}>
                <Text style={styles.tableTest}>{row.test}</Text>
                <Text style={styles.tableResult}>
                  {row.result}
                  {row.unit ? ` ${row.unit}` : ''}
                </Text>
              </View>
              <View style={styles.tableMeta}>
                {row.reference ? (
                  <Text style={styles.tableReference}>Ref: {row.reference}</Text>
                ) : null}
                {row.flag ? (
                  <Text style={[styles.flagBadge, flagStyle(row.flag)]}>{row.flag}</Text>
                ) : (
                  <Text style={styles.tableDash}>—</Text>
                )}
              </View>
            </View>
          ))}

          {section.type === 'paragraphs' && section.paragraphs?.map((paragraph, paragraphIndex) => (
            <Text key={`p-${sectionIndex}-${paragraphIndex}`} style={styles.paragraph}>
              • {paragraph}
            </Text>
          ))}
        </View>
      ))}
    </View>
  );
}

const styles = StyleSheet.create({
  panel: {
    backgroundColor: colors.background,
    borderColor: colors.border,
    borderRadius: 8,
    borderWidth: 1,
    gap: spacing.sm,
    padding: spacing.sm,
  },
  summary: {
    color: colors.text,
    fontSize: 13,
    lineHeight: 18,
  },
  section: {
    borderTopColor: colors.border,
    borderTopWidth: 1,
    gap: spacing.xs,
    paddingTop: spacing.sm,
  },
  sectionTitle: {
    color: colors.textMuted,
    fontSize: 11,
    fontWeight: '700',
    letterSpacing: 0.5,
    textTransform: 'uppercase',
  },
  fieldRow: {
    gap: 2,
  },
  fieldLabel: {
    color: colors.textMuted,
    fontSize: 11,
    fontWeight: '600',
    textTransform: 'uppercase',
  },
  fieldValue: {
    color: colors.text,
    fontSize: 13,
  },
  tableRow: {
    backgroundColor: colors.surface,
    borderColor: colors.border,
    borderRadius: 6,
    borderWidth: 1,
    flexDirection: 'row',
    gap: spacing.sm,
    justifyContent: 'space-between',
    padding: spacing.sm,
  },
  tableMain: {
    flex: 1,
    gap: 2,
  },
  tableTest: {
    color: colors.text,
    fontSize: 13,
    fontWeight: '600',
  },
  tableResult: {
    color: colors.text,
    fontSize: 13,
  },
  tableMeta: {
    alignItems: 'flex-end',
    gap: 4,
  },
  tableReference: {
    color: colors.textMuted,
    fontSize: 11,
  },
  tableDash: {
    color: colors.textMuted,
    fontSize: 12,
  },
  flagBadge: {
    borderRadius: 4,
    fontSize: 10,
    fontWeight: '700',
    overflow: 'hidden',
    paddingHorizontal: 6,
    paddingVertical: 2,
  },
  flagHigh: {
    backgroundColor: '#fee2e2',
    color: '#b91c1c',
  },
  flagLow: {
    backgroundColor: '#fef3c7',
    color: '#b45309',
  },
  flagNeutral: {
    backgroundColor: '#e2e8f0',
    color: '#475569',
  },
  paragraph: {
    color: colors.textMuted,
    fontSize: 12,
    lineHeight: 17,
  },
});
