import { useEffect, useRef, useState } from "react";
import { StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { BlurView } from "expo-blur";

import Colors from "@/constants/colors";
import { useQuietMode } from "@/lib/privacy/quiet-mode";
import { hapticSelection } from "@/lib/ui/haptics";

const PEEK_DURATION_MS = 4000;

interface QuietAmountProps {
  children: React.ReactNode;
  style?: object;
}

// Wrap any amount in this and it'll blur itself out whenever Quiet Screen
// Mode is on, with a tap unblurring it for a few seconds at a time. When
// the mode is off this is a no-op pass-through, so wrapping something in
// it costs nothing the rest of the time.
export function QuietAmount({ children, style }: QuietAmountProps) {
  const quietModeOn = useQuietMode((s) => s.enabled);
  const [peeking, setPeeking] = useState(false);
  const hideTimer = useRef<ReturnType<typeof setTimeout> | null>(null);

  useEffect(() => {
    if (!quietModeOn) setPeeking(false);
  }, [quietModeOn]);

  useEffect(() => {
    return () => {
      if (hideTimer.current) clearTimeout(hideTimer.current);
    };
  }, []);

  function handlePeek() {
    hapticSelection();
    setPeeking(true);
    if (hideTimer.current) clearTimeout(hideTimer.current);
    hideTimer.current = setTimeout(() => setPeeking(false), PEEK_DURATION_MS);
  }

  if (!quietModeOn) {
    return <>{children}</>;
  }

  if (peeking) {
    return (
      <TouchableOpacity activeOpacity={0.8} onPress={handlePeek} style={style}>
        {children}
      </TouchableOpacity>
    );
  }

  return (
    <TouchableOpacity activeOpacity={0.85} onPress={handlePeek} style={[styles.wrap, style]}>
      <View pointerEvents="none">{children}</View>
      <BlurView intensity={70} tint="dark" style={StyleSheet.absoluteFill} />
      <View style={styles.hintRow} pointerEvents="none">
        <Text style={styles.hintText}>tap to peek</Text>
      </View>
    </TouchableOpacity>
  );
}

const styles = StyleSheet.create({
  wrap: {
    borderRadius: 8,
    overflow: "hidden",
  },
  hintRow: {
    ...StyleSheet.absoluteFillObject,
    alignItems: "center" as const,
    justifyContent: "center" as const,
  },
  hintText: {
    fontSize: 11,
    fontWeight: "700" as const,
    color: Colors.dark.background,
    backgroundColor: "rgba(0,0,0,0.35)",
    paddingHorizontal: 8,
    paddingVertical: 3,
    borderRadius: 6,
    overflow: "hidden",
  },
});
