import { useEffect, useRef } from "react";
import { Animated, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";

import Colors from "@/constants/colors";
import { useDemoLedger } from "@/lib/demo-ledger";
import { hapticSuccess } from "@/lib/ui/haptics";

const VISIBLE_MS = 2600;

// Auto-Thank You - sits at the root of the app and watches the ledger for
// lastThankYou. The moment someone pays us, this pops a little "thanks,
// sent automatically" burst near the top of the screen and then clears
// itself out, no thread, no typing required from us.
export function ThankYouBurst() {
  const insets = useSafeAreaInsets();
  const lastThankYou = useDemoLedger((s) => s.lastThankYou);
  const clearThankYou = useDemoLedger((s) => s.clearThankYou);
  const translateY = useRef(new Animated.Value(-80)).current;
  const opacity = useRef(new Animated.Value(0)).current;
  const dismissTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    if (!lastThankYou) return;

    hapticSuccess();
    translateY.setValue(-80);
    opacity.setValue(0);

    Animated.parallel([
      Animated.spring(translateY, { toValue: 0, friction: 7, tension: 60, useNativeDriver: true }),
      Animated.timing(opacity, { toValue: 1, duration: 220, useNativeDriver: true }),
    ]).start();

    if (dismissTimer.current) clearTimeout(dismissTimer.current);
    dismissTimer.current = setTimeout(() => dismiss(), VISIBLE_MS);

    return () => {
      if (dismissTimer.current) clearTimeout(dismissTimer.current);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [lastThankYou?.transactionId]);

  function dismiss() {
    Animated.parallel([
      Animated.timing(translateY, { toValue: -80, duration: 220, useNativeDriver: true }),
      Animated.timing(opacity, { toValue: 0, duration: 220, useNativeDriver: true }),
    ]).start(() => clearThankYou());
  }

  if (!lastThankYou) return null;

  return (
    <View style={[styles.container, { top: insets.top + 8 }]} pointerEvents="box-none">
      <Animated.View
        style={[styles.card, { opacity, transform: [{ translateY }] }]}
      >
        <TouchableOpacity activeOpacity={0.85} onPress={dismiss} style={styles.cardInner}>
          <Text style={styles.emoji}>🙏</Text>
          <View style={styles.textWrap}>
            <Text style={styles.title}>Thanks sent automatically</Text>
            <Text style={styles.subtitle}>Zendo let {lastThankYou.name} know you got it</Text>
          </View>
        </TouchableOpacity>
      </Animated.View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    position: "absolute" as const,
    left: 16,
    right: 16,
    zIndex: 999,
    alignItems: "center" as const,
  },
  card: {
    width: "100%",
    maxWidth: 420,
    backgroundColor: Colors.dark.primary,
    borderRadius: 16,
    shadowColor: "#000",
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.25,
    shadowRadius: 10,
    elevation: 8,
  },
  cardInner: {
    flexDirection: "row" as const,
    alignItems: "center" as const,
    gap: 12,
    paddingVertical: 14,
    paddingHorizontal: 16,
  },
  emoji: {
    fontSize: 26,
  },
  textWrap: {
    flex: 1,
  },
  title: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: "#FFFFFF",
  },
  subtitle: {
    fontSize: 12,
    color: "rgba(255,255,255,0.85)",
    marginTop: 2,
  },
});
