import React, { useMemo } from 'react';
import { View, StyleSheet, ScrollView } from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import { Ionicons } from '@expo/vector-icons';
import { colors, spacing, radii, shadows } from '../../theme/tokens';
import { H1, H2, H3, Body, Caption, Button, Card, Badge } from '../../components/ui';
import { t } from '../../i18n';
import { useQuizStore } from '../../store';
import { calculateEquity, formatRatio } from '../../utils/equityCalculator';
import { formatCurrency } from '../../utils/format';

interface Props { onNext: () => void }

export function QuizStep5({ onNext }: Props) {
  const { incomeA, incomeB, charges, domesticA, domesticB, partnerAName, partnerBName } = useQuizStore();

  const totalCharges = useMemo(() =>
    Object.values(charges).reduce((sum, v) => sum + (v || 0), 0),
    [charges]
  );

  const result = useMemo(() => calculateEquity({
    incomeA: incomeA.netMonthly || 0,
    incomeB: incomeB.netMonthly || 0,
    commonCharges: totalCharges,
    domesticHoursA: domesticA.hoursPerWeek || 0,
    domesticHoursB: domesticB.hoursPerWeek || 0,
    domesticHourlyRate: 18,
  }), [incomeA, incomeB, totalCharges, domesticA, domesticB]);

  return (
    <ScrollView style={styles.container} contentContainerStyle={styles.scrollContent} showsVerticalScrollIndicator={false}>
      <H2>{t('quiz.step5Title')}</H2>
      <Body style={styles.subtitle} color={colors.neutral[500]}>
        {t('quiz.step5Subtitle')}
      </Body>

      {/* Main result card */}
      <LinearGradient
        colors={[colors.primary[700], colors.primary[900]]}
        style={styles.resultCard}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
      >
        <Caption style={styles.resultLabel}>{t('quiz.equityResult')}</Caption>
        <H1 style={styles.resultRatio} align="center">
          {formatRatio(result.adjustedRatioA, result.adjustedRatioB)}
        </H1>
        <Body style={styles.resultExplanation} align="center">
          {t(`equity.${result.explanation === 'near_equal' ? 'nearEqual'
            : result.explanation === 'a_contributes_more' ? 'aContributesMore'
            : result.explanation === 'b_contributes_more' ? 'bContributesMore'
            : 'equalNoIncome'}`)}
        </Body>
      </LinearGradient>

      {/* Details */}
      <Card style={styles.detailCard}>
        <View style={styles.detailRow}>
          <Caption>{t('equity.rawRatio')}</Caption>
          <Body style={styles.detailValue}>
            {formatRatio(result.ratioA, result.ratioB)}
          </Body>
        </View>
        <View style={styles.separator} />
        <View style={styles.detailRow}>
          <Caption>{t('equity.adjustedRatio')}</Caption>
          <Body style={styles.detailValue}>
            {formatRatio(result.adjustedRatioA, result.adjustedRatioB)}
          </Body>
        </View>
        <View style={styles.separator} />
        <View style={styles.detailRow}>
          <Caption>{t('equity.domesticValue')} — {partnerAName}</Caption>
          <Body style={styles.detailValue}>
            {formatCurrency(result.domesticValueA)} {t('equity.perMonth')}
          </Body>
        </View>
        <View style={styles.separator} />
        <View style={styles.detailRow}>
          <Caption>{t('equity.domesticValue')} — {partnerBName}</Caption>
          <Body style={styles.detailValue}>
            {formatCurrency(result.domesticValueB)} {t('equity.perMonth')}
          </Body>
        </View>
      </Card>

      {/* Disclaimer */}
      <View style={styles.disclaimerBox}>
        <Ionicons name="information-circle-outline" size={20} color={colors.neutral[500]} />
        <Caption style={styles.disclaimerText}>
          {t('quiz.disclaimer')}
        </Caption>
      </View>

      <View style={styles.footer}>
        <Button title={t('common.next')} onPress={onNext} fullWidth size="lg" />
      </View>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1 },
  scrollContent: {
    paddingHorizontal: spacing.xl,
    paddingBottom: spacing['5xl'],
  },
  subtitle: { marginTop: spacing.xs, marginBottom: spacing['2xl'] },
  resultCard: {
    borderRadius: radii['3xl'],
    padding: spacing['3xl'],
    alignItems: 'center',
    marginBottom: spacing.xl,
    ...shadows.lg,
  },
  resultLabel: {
    color: 'rgba(255,255,255,0.7)',
    textTransform: 'uppercase',
    letterSpacing: 2,
    marginBottom: spacing.md,
  },
  resultRatio: {
    color: '#FFFFFF',
    fontSize: 48,
    marginBottom: spacing.md,
  },
  resultExplanation: {
    color: 'rgba(255,255,255,0.85)',
    fontSize: 14,
  },
  detailCard: {
    padding: spacing.xl,
    marginBottom: spacing.lg,
  },
  detailRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingVertical: spacing.md,
  },
  detailValue: {
    fontWeight: '600',
    color: colors.neutral[900],
  },
  separator: {
    height: 1,
    backgroundColor: colors.neutral[100],
  },
  disclaimerBox: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    gap: spacing.sm,
    padding: spacing.lg,
    backgroundColor: colors.neutral[50],
    borderRadius: radii.xl,
  },
  disclaimerText: { flex: 1, lineHeight: 18 },
  footer: { marginTop: spacing['2xl'] },
});
