import { useRef, useState } from "react";
import { Animated, StyleSheet, Text, TouchableOpacity, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { Stack, useRouter } from "expo-router";
import { CheckCircle2, Smartphone } from "lucide-react-native";

import Colors from "@/constants/colors";
import { useAuth } from "@/lib/auth-context";
import { hapticHeavy, hapticSuccess } from "@/lib/ui/haptics";

const NEARBY_CANDIDATES = [
  { name: "Priya Patel", username: "priya_p", avatar: "https://i.pravatar.cc/150?img=29" },
  { name: "Sam O'Brien", username: "sam_ob", avatar: "https://i.pravatar.cc/150?img=8" },
  { name: "Lena Kowalski", username: "lena_k", avatar: "https://i.pravatar.cc/150?img=37" },
];

// Tap-to-Share Handle - real NFC needs actual hardware on both phones, so
// this simulates the moment of contact with a "hold near each other" pulse
// and a button standing in for the tap itself. Once it "detects" someone,
// the handle exchange happens instantly, no typing a username required.
export default function TapShareScreen() {
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const { user } = useAuth();
  const [connected, setConnected] = useState<typeof NEARBY_CANDIDATES[number] | null>(null);
  const [isListening, setIsListening] = useState(false);
  const pulse = useRef(new Animated.Value(1)).current;

  const startListening = () => {
    setIsListening(true);
    hapticHeavy();
    Animated.loop(
      Animated.sequence([
        Animated.timing(pulse, { toValue: 1.25, duration: 500, useNativeDriver: true }),
        Animated.timing(pulse, { toValue: 1, duration: 500, useNativeDriver: true }),
      ])
    ).start();

    setTimeout(() => {
      const match = NEARBY_CANDIDATES[Math.floor(Math.random() * NEARBY_CANDIDATES.length)];
      setConnected(match);
      setIsListening(false);
      pulse.stopAnimation();
      pulse.setValue(1);
      hapticSuccess();
    }, 1400);
  };

  const handleReset = () => {
    setConnected(null);
  };

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <Stack.Screen options={{ title: "Tap to Share", headerShown: true }} />

      <View style={styles.content}>
        {connected ? (
          <View style={styles.resultCard}>
            <CheckCircle2 color={Colors.dark.success} size={56} />
            <Text style={styles.resultTitle}>Handles exchanged</Text>
            <Text style={styles.resultSubtitle}>
              You and {connected.name} now have each other's @handle - no typing required.
            </Text>
            <View style={styles.handleRow}>
              <View style={styles.handleBox}>
                <Text style={styles.handleLabel}>You</Text>
                <Text style={styles.handleValue}>@{user?.username || "you"}</Text>
              </View>
              <View style={styles.handleBox}>
                <Text style={styles.handleLabel}>{connected.name}</Text>
                <Text style={styles.handleValue}>@{connected.username}</Text>
              </View>
            </View>
            <TouchableOpacity
              style={styles.primaryButton}
              onPress={() => router.push(`/send?username=${connected.username}`)}
              activeOpacity={0.85}
            >
              <Text style={styles.primaryButtonText}>Send {connected.name} Money</Text>
            </TouchableOpacity>
            <TouchableOpacity onPress={handleReset} style={styles.secondaryAction}>
              <Text style={styles.secondaryActionText}>Tap with someone else</Text>
            </TouchableOpacity>
          </View>
        ) : (
          <>
            <Animated.View style={[styles.pulseCircle, { transform: [{ scale: pulse }] }]}>
              <Smartphone color={Colors.dark.primary} size={48} />
            </Animated.View>
            <Text style={styles.instructionTitle}>
              {isListening ? "Hold steady..." : "Hold your phone near theirs"}
            </Text>
            <Text style={styles.instructionSubtitle}>
              Both of you open this screen and tap "Simulate Tap" - Zendo trades @handles instantly over the connection.
            </Text>
            <TouchableOpacity
              style={[styles.primaryButton, isListening && styles.primaryButtonDisabled]}
              onPress={startListening}
              disabled={isListening}
              activeOpacity={0.85}
            >
              <Text style={styles.primaryButtonText}>{isListening ? "Detecting..." : "Simulate Tap"}</Text>
            </TouchableOpacity>
          </>
        )}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.dark.background,
  },
  content: {
    flex: 1,
    alignItems: "center" as const,
    justifyContent: "center" as const,
    paddingHorizontal: 32,
  },
  pulseCircle: {
    width: 120,
    height: 120,
    borderRadius: 60,
    backgroundColor: `${Colors.dark.primary}14`,
    alignItems: "center" as const,
    justifyContent: "center" as const,
    marginBottom: 28,
  },
  instructionTitle: {
    fontSize: 19,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    marginBottom: 10,
  },
  instructionSubtitle: {
    fontSize: 14,
    color: Colors.dark.textSecondary,
    textAlign: "center" as const,
    lineHeight: 20,
    marginBottom: 28,
  },
  primaryButton: {
    backgroundColor: Colors.dark.primary,
    paddingHorizontal: 28,
    paddingVertical: 16,
    borderRadius: 16,
    width: "100%",
    alignItems: "center" as const,
  },
  primaryButtonDisabled: {
    opacity: 0.6,
  },
  primaryButtonText: {
    fontSize: 15,
    fontWeight: "700" as const,
    color: "#FFFFFF",
  },
  resultCard: {
    alignItems: "center" as const,
    width: "100%",
  },
  resultTitle: {
    fontSize: 20,
    fontWeight: "700" as const,
    color: Colors.dark.text,
    marginTop: 16,
    marginBottom: 8,
  },
  resultSubtitle: {
    fontSize: 14,
    color: Colors.dark.textSecondary,
    textAlign: "center" as const,
    lineHeight: 20,
    marginBottom: 24,
  },
  handleRow: {
    flexDirection: "row" as const,
    gap: 12,
    width: "100%",
    marginBottom: 28,
  },
  handleBox: {
    flex: 1,
    backgroundColor: Colors.dark.surface,
    borderRadius: 14,
    borderWidth: 1,
    borderColor: Colors.dark.border,
    padding: 14,
    alignItems: "center" as const,
  },
  handleLabel: {
    fontSize: 12,
    color: Colors.dark.textSecondary,
    marginBottom: 4,
  },
  handleValue: {
    fontSize: 14,
    fontWeight: "700" as const,
    color: Colors.dark.primary,
  },
  secondaryAction: {
    marginTop: 16,
  },
  secondaryActionText: {
    fontSize: 13,
    fontWeight: "600" as const,
    color: Colors.dark.textSecondary,
  },
});
