import { useEffect, useRef, type ReactNode } from 'react';
import { ActivityIndicator, Animated, Pressable, StyleSheet, Text, TextInput, View, type TextInputProps, type ViewStyle } from 'react-native';
import { font, useTheme } from './theme';
import { useSession } from './store';

export function T({ children, style, size = 14, weight = 'reg', color, center, numberOfLines }:
  { children: ReactNode; style?: any; size?: number; weight?: keyof typeof font; color?: string; center?: boolean; numberOfLines?: number }) {
  const th = useTheme(); const { rtl } = useSession();
  return <Text numberOfLines={numberOfLines} style={[{ fontFamily: font[weight], fontSize: size, color: color ?? th.ink,
    textAlign: center ? 'center' : rtl ? 'right' : 'left', writingDirection: rtl ? 'rtl' : 'ltr' }, style]}>{children}</Text>;
}

export function Button({ title, onPress, loading, kind = 'primary', style, disabled }:
  { title: string; onPress: () => void; loading?: boolean; kind?: 'primary' | 'ghost' | 'danger' | 'outline'; style?: ViewStyle; disabled?: boolean }) {
  const th = useTheme();
  const bg = kind === 'primary' ? th.acc : kind === 'danger' ? th.red : 'transparent';
  const fg = kind === 'primary' || kind === 'danger' ? '#fff' : th.acc;
  return (
    <Pressable onPress={onPress} disabled={loading || disabled} accessibilityRole="button"
      style={({ pressed }) => [{ height: kind === 'ghost' ? 44 : 52, borderRadius: 16, backgroundColor: bg, alignItems: 'center', justifyContent: 'center',
        flexDirection: 'row', gap: 8, opacity: disabled ? 0.5 : 1, transform: [{ scale: pressed ? 0.97 : 1 }],
        borderWidth: kind === 'outline' ? 1.5 : 0, borderColor: th.acc }, style]}>
      {loading && <ActivityIndicator color={fg} />}
      <T weight="semi" size={kind === 'ghost' ? 13.5 : 15} color={fg}>{title}</T>
    </Pressable>
  );
}

export function Field({ label, prefix, right, ...p }: TextInputProps & { label: string; prefix?: string; right?: ReactNode }) {
  const th = useTheme(); const { rtl } = useSession();
  return (
    <View style={{ gap: 6 }}>
      {!!label && <T size={11} weight="semi" color={th.muted}>{label}</T>}
      <View style={{ flexDirection: 'row', alignItems: 'center', gap: 8, backgroundColor: th.bg, borderRadius: 14, paddingHorizontal: 14, height: 50 }}>
        {prefix && <T weight="semi" color={th.muted}>{prefix}</T>}
        <TextInput placeholderTextColor={th.muted} {...p}
          style={{ flex: 1, fontFamily: font.reg, fontSize: 15, color: th.ink, textAlign: rtl && p.keyboardType !== 'phone-pad' ? 'right' : 'left' }} />
        {right}
      </View>
    </View>
  );
}

export function Chip({ label, on, onPress, color }: { label: string; on: boolean; onPress: () => void; color?: string }) {
  const th = useTheme(); const c = color ?? th.acc;
  return (
    <Pressable onPress={onPress} accessibilityRole="button" accessibilityState={{ selected: on }}
      style={{ paddingVertical: 7, paddingHorizontal: 14, borderRadius: 99, borderWidth: 1, borderColor: on ? c : th.line, backgroundColor: on ? c : 'transparent' }}>
      <T size={12.5} weight="semi" color={on ? '#fff' : th.muted}>{label}</T>
    </Pressable>
  );
}

export function LineBadge({ code, color, size = 54 }: { code: string; color: string; size?: number }) {
  return (
    <View style={{ width: size, height: size, borderRadius: size * 0.3, backgroundColor: color, alignItems: 'center', justifyContent: 'center' }}>
      <T weight="bold" size={size * 0.4} color="#fff">{code}</T>
    </View>
  );
}

export function LiveDot({ color }: { color: string }) {
  const a = useRef(new Animated.Value(1)).current;
  useEffect(() => {
    const loop = Animated.loop(Animated.sequence([
      Animated.timing(a, { toValue: 0.35, duration: 800, useNativeDriver: true }),
      Animated.timing(a, { toValue: 1, duration: 800, useNativeDriver: true })]));
    loop.start(); return () => loop.stop();
  }, [a]);
  return <Animated.View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: color, opacity: a }} />;
}

export function Bar({ value, color, height = 6 }: { value: number; color: string; height?: number }) {
  const th = useTheme();
  return (
    <View style={{ height, borderRadius: height, backgroundColor: th.line, overflow: 'hidden' }}>
      <View style={{ width: `${Math.max(0, Math.min(1, value)) * 100}%`, height: '100%', backgroundColor: color, borderRadius: height }} />
    </View>
  );
}

export function BusGlyph({ size = 24, color = '#fff', inner = '#1B4F8A' }: { size?: number; color?: string; inner?: string }) {
  // pictogramme du bus des prototypes, en vues simples (pas besoin de librairie SVG)
  const u = size / 24;
  return (
    <View style={{ width: size, height: size }}>
      <View style={{ position: 'absolute', left: 3 * u, top: 3 * u, width: 18 * u, height: 14 * u, borderRadius: 3.5 * u, backgroundColor: color }} />
      <View style={{ position: 'absolute', left: 5 * u, top: 5.5 * u, width: 14 * u, height: 5.5 * u, borderRadius: 1.2 * u, backgroundColor: inner }} />
      <View style={{ position: 'absolute', left: 5 * u, top: 17.8 * u, width: 4 * u, height: 4 * u, borderRadius: 2 * u, backgroundColor: color }} />
      <View style={{ position: 'absolute', left: 15 * u, top: 17.8 * u, width: 4 * u, height: 4 * u, borderRadius: 2 * u, backgroundColor: color }} />
    </View>
  );
}

export const s = StyleSheet.create({ fill: { flex: 1 } });
