import React, { useMemo } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { Runner } from '../types';
import { useTheme, Theme } from '../theme/ThemeContext';

interface RunnerRowProps {
  runner: Runner;
  showDetails?: boolean;
}

// ── Mini bar for win/place probability ─────────────────────────────────
const MiniBar = ({
  value,
  label,
  color,
  theme,
}: {
  value: number;
  label: string;
  color: string;
  theme: Theme;
}) => {
  const s = useMemo(() => createStyles(theme), [theme]);
  return (
    <View style={s.miniBarRow}>
      <Text style={s.miniBarLabel}>{label}</Text>
      <View style={s.miniBarTrack}>
        <View style={[s.miniBarFill, { width: `${Math.min(value, 100)}%`, backgroundColor: color }]} />
      </View>
      <Text style={s.miniBarValue}>{value.toFixed(1)}%</Text>
    </View>
  );
};

// ── Form trend dots (last 4 positions) ─────────────────────────────────
const FormDots = ({ form, theme }: { form: string; theme: Theme }) => {
  const s = useMemo(() => createStyles(theme), [theme]);
  const parts = form.split('-').filter(Boolean);
  const positions = parts.map(Number);
  const isValid = positions.length > 0 && positions.every((n) => !isNaN(n));

  if (!isValid) return null;

  return (
    <View style={s.formContainer}>
      <Text style={s.footerLabel}>Form:</Text>
      <View style={s.formDots}>
        {positions.map((pos, i) => (
          <View
            key={i}
            style={[
              s.formDot,
              pos === 1
                ? s.formDotWin
                : pos <= 3
                  ? s.formDotPlace
                  : pos <= 5
                    ? s.formDotClose
                    : s.formDotOther,
            ]}
          />
        ))}
      </View>
      <Text style={s.formText}>({form})</Text>
    </View>
  );
};

// ── Barrier advantage indicator ────────────────────────────────────────
const BarrierIndicator = ({ barrier }: { barrier: number }) => {
  let color: string;
  let icon: keyof typeof Ionicons.glyphMap;
  let label: string;

  if (barrier <= 3) {
    color = '#22c55e';
    icon = 'checkmark-circle';
    label = 'Good';
  } else if (barrier <= 6) {
    color = '#eab308';
    icon = 'remove-circle';
    label = 'Neutral';
  } else {
    color = '#ef4444';
    icon = 'alert-circle';
    label = 'Wide';
  }

  return (
    <View style={styles.barrierContainer}>
      <Text style={styles.footerLabel}>Barrier:</Text>
      <Ionicons name={icon} size={14} color={color} />
      <Text style={[styles.barrierValue, { color }]}>{label} ({barrier})</Text>
    </View>
  );
};

// ── Runner row component ───────────────────────────────────────────────
export const RunnerRow: React.FC<RunnerRowProps> = ({ runner, showDetails = true }) => {
  const { theme } = useTheme();
  const styles = useMemo(() => createStyles(theme), [theme]);
  const showRiderInfo = showDetails && (runner.rider || runner.trainer);

  return (
    <View style={styles.container}>
      {/* Header: number badge, name, badges */}
      <View style={styles.header}>
        <View style={styles.numberBadge}>
          <Text style={styles.number}>{runner.number}</Text>
        </View>
        <View style={styles.nameSection}>
          <Text style={styles.name}>{runner.name}</Text>
          {showRiderInfo && (
            <Text style={styles.details}>
              {runner.rider ? `${runner.rider} \u2022 ` : ''}{runner.trainer}
            </Text>
          )}
        </View>
        <View style={styles.badges}>
          {(runner.badges || []).slice(0, 2).map((badge, index) => (
            <View key={index} style={styles.badge}>
              <Text style={styles.badgeText}>{badge}</Text>
            </View>
          ))}
        </View>
      </View>

      {/* Probability bars */}
      <View style={styles.gauges}>
        <MiniBar value={runner.win_probability} label="Win" color="#22c55e" theme={theme} />
        <MiniBar value={runner.place_probability} label="Place" color="#3b82f6" theme={theme} />
      </View>

      {/* Footer: form trend + barrier indicator */}
      <View style={styles.footer}>
        <FormDots form={runner.form} theme={theme} />
        <BarrierIndicator barrier={runner.barrier} />
      </View>
    </View>
  );
};

// ── Styles ─────────────────────────────────────────────────────────────
const createStyles = (theme: Theme) =>
  StyleSheet.create({
    container: {
      backgroundColor: theme.card,
      borderRadius: 12,
      padding: 14,
      marginBottom: 10,
      borderWidth: 1,
      borderColor: theme.border,
    },

    /* Header */
    header: {
      flexDirection: 'row',
      alignItems: 'center',
      marginBottom: 10,
    },
    numberBadge: {
      width: 32,
      height: 32,
      borderRadius: 16,
      backgroundColor: theme.primary,
      alignItems: 'center',
      justifyContent: 'center',
      marginRight: 12,
    },
    number: {
      color: theme.primaryText,
      fontSize: 14,
      fontWeight: '700',
    },
    nameSection: {
      flex: 1,
    },
    name: {
      fontSize: 16,
      fontWeight: '600',
      color: theme.text,
    },
    details: {
      fontSize: 12,
      color: theme.textSecondary,
      marginTop: 2,
    },
    badges: {
      flexDirection: 'row',
      gap: 4,
    },
    badge: {
      backgroundColor: '#fef3c7',
      paddingHorizontal: 8,
      paddingVertical: 4,
      borderRadius: 12,
    },
    badgeText: {
      fontSize: 10,
      fontWeight: '600',
      color: '#92400e',
    },

    /* Probability bars (MiniBar) */
    gauges: {
      gap: 6,
      marginBottom: 10,
    },
    miniBarRow: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 8,
    },
    miniBarLabel: {
      fontSize: 11,
      fontWeight: '700',
      color: theme.textTertiary,
      width: 42,
    },
    miniBarTrack: {
      flex: 1,
      height: 10,
      backgroundColor: theme.chipBg,
      borderRadius: 5,
      overflow: 'hidden',
    },
    miniBarFill: {
      height: '100%',
      borderRadius: 5,
    },
    miniBarValue: {
      fontSize: 12,
      fontWeight: '600',
      color: theme.chipText,
      width: 50,
      textAlign: 'right',
    },

    /* Footer row */
    footer: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
    },
    footerLabel: {
      fontSize: 11,
      fontWeight: '600',
      color: theme.textTertiary,
      marginRight: 4,
    },

    /* Form dots */
    formContainer: {
      flexDirection: 'row',
      alignItems: 'center',
    },
    formDots: {
      flexDirection: 'row',
      gap: 3,
      marginRight: 4,
    },
    formDot: {
      width: 8,
      height: 8,
      borderRadius: 4,
    },
    formDotWin: {
      backgroundColor: '#22c55e',
    },
    formDotPlace: {
      backgroundColor: '#3b82f6',
    },
    formDotClose: {
      backgroundColor: '#eab308',
    },
    formDotOther: {
      backgroundColor: '#d1d5db',
    },
    formText: {
      fontSize: 11,
      color: theme.textTertiary,
    },

    /* Barrier indicator */
    barrierContainer: {
      flexDirection: 'row',
      alignItems: 'center',
      gap: 4,
    },
    barrierValue: {
      fontSize: 12,
      fontWeight: '600',
    },
  });

// Static reference for BarrierIndicator which doesn't use theme
const styles = createStyles({
  background: '#f9fafb',
  card: '#ffffff',
  text: '#111827',
  textSecondary: '#6b7280',
  textTertiary: '#9ca3af',
  border: '#e5e7eb',
  borderLight: '#f3f4f6',
  primary: '#111827',
  primaryText: '#ffffff',
  accent: '#06b6d4',
  danger: '#dc2626',
  chipBg: '#f3f4f6',
  chipText: '#374151',
  chipActiveBg: '#111827',
  chipActiveText: '#ffffff',
});