import React, { useEffect } from "react";
import { ScrollView, StyleSheet, View } from "react-native";
import type { NativeStackScreenProps } from "@react-navigation/native-stack";
import { BottleOverlay } from "../components/BottleOverlay";
import { CharacterView } from "../components/CharacterView";
import { ConversationButton } from "../components/ConversationButton";
import { LoadingView } from "../components/LoadingView";
import { trackMetric } from "../api/metricsApi";
import { useProductStore } from "../store/productStore";
import { useConversationStore } from "../store/conversationStore";
import type { RootStackParamList } from "../navigation/types";

type Props = NativeStackScreenProps<RootStackParamList, "Bottle">;

export function BottleScreen({ navigation }: Props) {
  const product = useProductStore((s) => s.product);
  const characterState = useConversationStore((s) => s.characterState);

  useEffect(() => {
    if (!product) return;
    trackMetric({
      event: "character_activated",
      product_id: product.id,
      character_id: product.character_id,
    }).catch(() => undefined);
  }, [product]);

  if (!product) {
    return <LoadingView message="Sin producto. Escaneá un QR." />;
  }

  return (
    <ScrollView contentContainerStyle={styles.container}>
      <BottleOverlay product={product} />
      <View style={styles.character}>
        <CharacterView character={product.character} state={characterState} />
      </View>
      <ConversationButton onPress={() => navigation.navigate("Conversation")} />
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  container: {
    padding: 20,
    gap: 28,
    paddingBottom: 40,
  },
  character: {
    alignItems: "center",
    paddingVertical: 12,
  },
});
