import React, { useEffect, useRef } from "react";
import { Animated, Easing, StyleSheet, Text, View } from "react-native";
import type { Character, CharacterState } from "../types/Character";

const STATE_COPY: Record<CharacterState, string> = {
  idle: "Listo para conversar",
  listening: "Te estoy escuchando",
  thinking: "Pensando la respuesta",
  talking: "Don Mateo está hablando",
  happy: "¡Salud!",
  sad: "Hmm, veamos",
  surprised: "¡Qué sorpresa!",
};

const STATE_COLOR: Record<CharacterState, string> = {
  idle: "#C4A35A",
  listening: "#5AC4A3",
  thinking: "#A39BC4",
  talking: "#E07A3D",
  happy: "#E0C03D",
  sad: "#6E7F9A",
  surprised: "#E06B9A",
};

/**
 * Personaje 2D para el MVP. El contrato `state` se conserva para que el
 * renderer con tracking AR pueda reemplazarlo más adelante sin tocar voz ni
 * conversación.
 */
export function Character2D({
  character,
  state,
}: {
  character: Character;
  state: CharacterState;
}) {
  const bob = useRef(new Animated.Value(0)).current;
  const mouth = useRef(new Animated.Value(0.2)).current;
  const glow = useRef(new Animated.Value(0.25)).current;

  useEffect(() => {
    const isTalking = state === "talking";
    const isListening = state === "listening";
    const isThinking = state === "thinking";

    const bobLoop = Animated.loop(
      Animated.sequence([
        Animated.timing(bob, {
          toValue: isTalking ? -7 : isListening ? -4 : -3,
          duration: isTalking ? 180 : 1100,
          easing: Easing.inOut(Easing.sin),
          useNativeDriver: true,
        }),
        Animated.timing(bob, {
          toValue: 0,
          duration: isTalking ? 180 : 1100,
          easing: Easing.inOut(Easing.sin),
          useNativeDriver: true,
        }),
      ]),
    );
    const mouthLoop = Animated.loop(
      Animated.sequence([
        Animated.timing(mouth, {
          toValue: isTalking ? 1 : 0.2,
          duration: isTalking ? 130 : 250,
          useNativeDriver: false,
        }),
        Animated.timing(mouth, {
          toValue: isTalking ? 0.35 : 0.2,
          duration: isTalking ? 130 : 250,
          useNativeDriver: false,
        }),
      ]),
    );
    const glowLoop = Animated.loop(
      Animated.sequence([
        Animated.timing(glow, {
          toValue: isListening || isThinking || isTalking ? 0.85 : 0.35,
          duration: isThinking ? 550 : 800,
          useNativeDriver: false,
        }),
        Animated.timing(glow, {
          toValue: 0.25,
          duration: isThinking ? 550 : 800,
          useNativeDriver: false,
        }),
      ]),
    );

    bobLoop.start();
    mouthLoop.start();
    glowLoop.start();
    return () => {
      bobLoop.stop();
      mouthLoop.stop();
      glowLoop.stop();
    };
  }, [bob, glow, mouth, state]);

  const mouthHeight = mouth.interpolate({
    inputRange: [0, 1],
    outputRange: [5, 20],
  });
  const ringScale = glow.interpolate({
    inputRange: [0, 1],
    outputRange: [1, 1.14],
  });

  return (
    <View style={styles.wrap}>
      <Animated.View
        style={[
          styles.aura,
          {
            borderColor: STATE_COLOR[state],
            opacity: glow,
            transform: [{ scale: ringScale }],
          },
        ]}
      />
      <Animated.View style={[styles.character, { transform: [{ translateY: bob }] }]}>
        <View style={styles.hat}>
          <View style={styles.hatBand} />
        </View>
        <View style={styles.head}>
          <View style={[styles.ear, styles.leftEar]} />
          <View style={[styles.ear, styles.rightEar]} />
          <View style={styles.hair} />
          <View style={styles.eyebrows}>
            <View style={styles.eyebrow} />
            <View style={styles.eyebrow} />
          </View>
          <View style={styles.eyes}>
            <View style={styles.eye} />
            <View style={styles.eye} />
          </View>
          <View style={styles.nose} />
          <Animated.View style={[styles.mouth, { height: mouthHeight }]} />
          <View style={styles.mustache}>
            <View style={styles.mustacheSide} />
            <View style={[styles.mustacheSide, styles.mustacheRight]} />
          </View>
        </View>
        <View style={styles.neck} />
        <View style={styles.body}>
          <View style={styles.shirt} />
          <View style={styles.apron}>
            <Text style={styles.monogram}>M</Text>
          </View>
        </View>
      </Animated.View>
      <Text style={styles.name}>{character.name}</Text>
      <View style={[styles.status, { borderColor: STATE_COLOR[state] }]}>
        <View style={[styles.statusDot, { backgroundColor: STATE_COLOR[state] }]} />
        <Text style={styles.statusText}>{STATE_COPY[state]}</Text>
      </View>
      <Text style={styles.description}>{character.description}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  wrap: { alignItems: "center", minHeight: 330, justifyContent: "flex-end" },
  aura: {
    position: "absolute",
    top: 12,
    width: 220,
    height: 220,
    borderRadius: 110,
    borderWidth: 3,
    backgroundColor: "#C4A35A10",
  },
  character: { width: 184, alignItems: "center", zIndex: 1 },
  hat: {
    width: 138,
    height: 48,
    borderTopLeftRadius: 68,
    borderTopRightRadius: 68,
    backgroundColor: "#352414",
    borderWidth: 3,
    borderColor: "#160E08",
    justifyContent: "flex-end",
    overflow: "hidden",
    zIndex: 4,
  },
  hatBand: { height: 11, backgroundColor: "#C4A35A" },
  head: {
    width: 124,
    height: 139,
    marginTop: -4,
    backgroundColor: "#C88762",
    borderWidth: 3,
    borderColor: "#613724",
    borderRadius: 58,
    alignItems: "center",
    zIndex: 3,
  },
  ear: {
    position: "absolute",
    top: 63,
    width: 18,
    height: 29,
    borderRadius: 10,
    backgroundColor: "#B97052",
    borderWidth: 2,
    borderColor: "#613724",
  },
  leftEar: { left: -16 },
  rightEar: { right: -16 },
  hair: {
    position: "absolute",
    top: 6,
    width: 94,
    height: 29,
    backgroundColor: "#4A2A1A",
    borderTopLeftRadius: 42,
    borderTopRightRadius: 42,
  },
  eyebrows: { flexDirection: "row", gap: 25, marginTop: 43 },
  eyebrow: { width: 27, height: 5, borderRadius: 4, backgroundColor: "#4A2A1A", transform: [{ rotate: "-4deg" }] },
  eyes: { flexDirection: "row", gap: 30, marginTop: 7 },
  eye: { width: 10, height: 10, borderRadius: 5, backgroundColor: "#24140C" },
  nose: { width: 9, height: 12, marginTop: 7, borderRadius: 5, backgroundColor: "#AF654B" },
  mouth: { width: 27, marginTop: 7, borderRadius: 15, backgroundColor: "#6B2630", overflow: "hidden" },
  mustache: { position: "absolute", top: 103, flexDirection: "row", gap: 1 },
  mustacheSide: { width: 27, height: 12, borderRadius: 12, backgroundColor: "#442517", transform: [{ rotate: "9deg" }] },
  mustacheRight: { transform: [{ rotate: "-9deg" }] },
  neck: { width: 37, height: 19, marginTop: -2, backgroundColor: "#B97052", zIndex: 2 },
  body: {
    width: 177,
    height: 97,
    marginTop: -1,
    borderTopLeftRadius: 72,
    borderTopRightRadius: 72,
    backgroundColor: "#EEE1CB",
    overflow: "hidden",
    alignItems: "center",
  },
  shirt: { position: "absolute", width: 12, height: 102, backgroundColor: "#C4A35A" },
  apron: {
    position: "absolute",
    bottom: 0,
    width: 128,
    height: 57,
    borderTopLeftRadius: 22,
    borderTopRightRadius: 22,
    backgroundColor: "#573A24",
    alignItems: "center",
    justifyContent: "center",
  },
  monogram: { color: "#EACD83", fontWeight: "800", fontSize: 25 },
  name: { color: "#FFF8EC", fontSize: 24, fontWeight: "800", marginTop: 10 },
  status: { flexDirection: "row", alignItems: "center", gap: 7, borderWidth: 1, borderRadius: 14, paddingHorizontal: 11, paddingVertical: 5, marginTop: 6 },
  statusDot: { width: 7, height: 7, borderRadius: 4 },
  statusText: { color: "#D4CBB8", fontSize: 12 },
  description: { color: "#B8AFA0", textAlign: "center", marginTop: 8 },
});
