import type { ReactNode } from 'react';
import { Linking, Pressable, StyleSheet, Text, View } from 'react-native';
import {
  AskDrAiAnswer,
  displayAskDrAiText,
  hasAskDrAiSourceUrl,
  isAskDrAiNotFoundAnswer,
} from '../../services/askDrAi';
import { colors, spacing } from '../../constants/theme';
import { DocumentDisplayPanel } from './DocumentDisplayPanel';

type Props = {
  item: AskDrAiAnswer;
};

function fitPercentage(value: number) {
  return Math.max(0, Math.min(100, Math.round(Number(value) || 0)));
}

function BulletList({ items }: { items: string[] }) {
  return (
    <View style={styles.list}>
      {items.map((entry, index) => (
        <Text key={`${entry}-${index}`} style={styles.listItem}>
          {'\u2022 '}
          {entry}
        </Text>
      ))}
    </View>
  );
}

function NumberedList({ items }: { items: string[] }) {
  return (
    <View style={styles.list}>
      {items.map((entry, index) => (
        <Text key={`${entry}-${index}`} style={styles.listItem}>
          {index + 1}. {entry}
        </Text>
      ))}
    </View>
  );
}

function Section({
  title,
  children,
}: {
  title: string;
  children: ReactNode;
}) {
  return (
    <View style={styles.section}>
      <Text style={styles.sectionTitle}>{title}</Text>
      {children}
    </View>
  );
}

function EmptyValue() {
  return <Text style={styles.emptyValue}>N/A</Text>;
}

export function MatchedAnswerCard({ item }: Props) {
  const symptoms = (item.symptoms || []).map((entry) => String(entry).trim()).filter(Boolean);
  const fit = fitPercentage(item.fit_percentage);
  const notFound = isAskDrAiNotFoundAnswer(item);

  if (notFound) {
    return (
      <View style={[styles.card, styles.notFoundCard]}>
        <Text style={styles.title}>{item.title}</Text>
        <Text style={styles.body}>{displayAskDrAiText(item.answer)}</Text>
      </View>
    );
  }

  return (
    <View style={styles.card}>
      <View style={styles.headerRow}>
        <View style={styles.headerText}>
          <Text style={styles.title}>{item.title}</Text>
          <Text style={styles.sourceLabel}>{displayAskDrAiText(item.source_label)}</Text>
          {hasAskDrAiSourceUrl(item.source_url) ? (
            <Pressable onPress={() => Linking.openURL(item.source_url!)}>
              <Text style={styles.link}>View primary source</Text>
            </Pressable>
          ) : null}
        </View>
        <View style={styles.badge}>
          <Text style={styles.badgeText}>{fit}% fit</Text>
        </View>
      </View>

      <Text style={styles.body}>{displayAskDrAiText(item.answer)}</Text>

      <Section title="Common symptoms">
        {symptoms.length > 0 ? <BulletList items={symptoms} /> : <EmptyValue />}
      </Section>

      {item.document_display?.sections?.length ? (
        <Section title="Laboratory results from your upload">
          <DocumentDisplayPanel display={item.document_display} />
        </Section>
      ) : null}

      <Section title="Detailed information">
        <Text style={styles.bodySmall}>{displayAskDrAiText(item.detailed_information)}</Text>
      </Section>

      <Text style={styles.bodySmall}>
        <Text style={styles.bold}>Layman&apos;s term: </Text>
        {displayAskDrAiText(item.layman_term)}
      </Text>

      <Section title="Possible causes">
        {item.possible_causes?.length ? <BulletList items={item.possible_causes} /> : <EmptyValue />}
      </Section>

      <Section title="Treatment overview">
        {item.treatment_overview?.length ? <NumberedList items={item.treatment_overview} /> : <EmptyValue />}
      </Section>

      <Section title="Source links">
        {item.references?.length ? (
          <View style={styles.referenceList}>
            {item.references.map((ref, index) => (
              <View key={`${ref.url}-${index}`} style={styles.referenceItem}>
                <Pressable onPress={() => ref.url && Linking.openURL(ref.url)}>
                  <Text style={styles.link}>{ref.title || ref.url}</Text>
                </Pressable>
                {ref.url ? <Text style={styles.referenceUrl}>{ref.url}</Text> : null}
              </View>
            ))}
          </View>
        ) : (
          <EmptyValue />
        )}
      </Section>

      <Text style={styles.bodySmall}>
        <Text style={styles.bold}>Medical scientific name: </Text>
        {displayAskDrAiText(item.medical_scientific_name)}
      </Text>

      <Section title="Basic treatment steps">
        {item.basic_treatment_steps?.length ? (
          <NumberedList items={item.basic_treatment_steps} />
        ) : (
          <EmptyValue />
        )}
      </Section>

      <Section title="First-aid steps">
        {item.first_aid_steps?.length ? <NumberedList items={item.first_aid_steps} /> : <EmptyValue />}
      </Section>

      <View style={styles.progressTrack}>
        <View style={[styles.progressFill, { width: `${fit}%` }]} />
      </View>

      {item.matched_terms?.length ? (
        <Text style={styles.matchedTerms}>Matched terms: {item.matched_terms.join(', ')}</Text>
      ) : null}
    </View>
  );
}

const styles = StyleSheet.create({
  card: {
    backgroundColor: colors.surface,
    borderColor: colors.border,
    borderRadius: 12,
    borderWidth: 1,
    gap: spacing.sm,
    padding: spacing.md,
  },
  notFoundCard: {
    backgroundColor: '#fff8f0',
    borderColor: '#f0c987',
  },
  headerRow: {
    flexDirection: 'row',
    gap: spacing.sm,
    justifyContent: 'space-between',
  },
  headerText: {
    flex: 1,
    gap: 2,
  },
  title: {
    color: colors.text,
    fontSize: 16,
    fontWeight: '700',
  },
  sourceLabel: {
    color: colors.textMuted,
    fontSize: 12,
  },
  badge: {
    backgroundColor: colors.primary,
    borderRadius: 999,
    paddingHorizontal: 10,
    paddingVertical: 4,
  },
  badgeText: {
    color: '#fff',
    fontSize: 12,
    fontWeight: '700',
  },
  body: {
    color: colors.text,
    fontSize: 14,
    lineHeight: 20,
  },
  bodySmall: {
    color: colors.text,
    fontSize: 13,
    lineHeight: 19,
  },
  section: {
    gap: 4,
  },
  sectionTitle: {
    color: colors.text,
    fontSize: 13,
    fontWeight: '700',
  },
  emptyValue: {
    color: colors.textMuted,
    fontSize: 13,
  },
  list: {
    gap: 4,
  },
  listItem: {
    color: colors.text,
    fontSize: 13,
    lineHeight: 18,
  },
  bold: {
    fontWeight: '700',
  },
  link: {
    color: colors.primary,
    fontSize: 13,
    textDecorationLine: 'underline',
  },
  referenceList: {
    gap: spacing.xs,
  },
  referenceItem: {
    gap: 2,
  },
  referenceUrl: {
    color: colors.textMuted,
    fontSize: 11,
  },
  progressTrack: {
    backgroundColor: colors.border,
    borderRadius: 4,
    height: 6,
    overflow: 'hidden',
  },
  progressFill: {
    backgroundColor: colors.primary,
    height: '100%',
  },
  matchedTerms: {
    color: colors.textMuted,
    fontSize: 12,
  },
});
