import { scrollViewWebProps } from '@/lib/ui/scroll-props';
import { useState, useRef } from "react";
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  ScrollView,
  useWindowDimensions,
  Animated,
  Image,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useRouter } from "expo-router";
import AsyncStorage from "@react-native-async-storage/async-storage";
import {
  Shield,
  Zap,
  Globe,
  CreditCard,
  ArrowRight,
  CheckCircle2,
} from "lucide-react-native";
import Colors from "@/constants/colors";

const ONBOARDING_SEEN_KEY = "@zendo/onboarding_seen";

const slides = [
  {
    id: 1,
    title: "Secure Payments",
    description:
      "Bank-grade encryption and fraud detection keep your money safe with three-layer code obfuscation",
    icon: Shield,
    color: Colors.dark.success,
  },
  {
    id: 2,
    title: "Instant Transfers",
    description:
      "Send money to friends and family instantly with just their username. No delays, no hassle",
    icon: Zap,
    color: Colors.dark.primary,
  },
  {
    id: 3,
    title: "Global Reach",
    description:
      "Connect with anyone, anywhere. Split bills, pay merchants, and manage recurring payments",
    icon: Globe,
    color: "#3B82F6",
  },
  {
    id: 4,
    title: "Smart Fees",
    description:
      "Only $0.03 minimum or 1% max per transaction. Transparent pricing with no hidden charges",
    icon: CreditCard,
    color: "#8B5CF6",
  },
];

export default function OnboardingScreen() {
  const { width } = useWindowDimensions();
  const insets = useSafeAreaInsets();
  const router = useRouter();
  const [currentSlide, setCurrentSlide] = useState(0);
  const scrollX = useRef(new Animated.Value(0)).current;
  const slidesRef = useRef<ScrollView>(null);

  const handleNext = () => {
    if (currentSlide < slides.length - 1) {
      const nextSlide = currentSlide + 1;
      slidesRef.current?.scrollTo({
        x: nextSlide * width,
        animated: true,
      });
      setCurrentSlide(nextSlide);
    } else {
      finishOnboarding();
    }
  };

  const handleSkip = () => {
    finishOnboarding();
  };

  const finishOnboarding = () => {
    AsyncStorage.setItem(ONBOARDING_SEEN_KEY, "true").catch(() => {});
    router.replace("/auth");
  };

  return (
    <View style={[styles.container, { paddingTop: insets.top }]}>
      <View style={styles.logoContainer}>
        <Image
          source={require("../assets/images/zendo-logo.png")}
          style={styles.logo}
          resizeMode="contain"
        />
      </View>
      <TouchableOpacity style={styles.skipButton} onPress={handleSkip}>
        <Text style={styles.skipButtonText}>Skip</Text>
      </TouchableOpacity>

      <ScrollView
        ref={slidesRef}
        horizontal
        pagingEnabled
        showsHorizontalScrollIndicator={scrollViewWebProps.showsHorizontalScrollIndicator}
        onScroll={Animated.event(
          [{ nativeEvent: { contentOffset: { x: scrollX } } }],
          { useNativeDriver: false }
        )}
        scrollEventThrottle={16}
        onMomentumScrollEnd={(event) => {
          const slide = Math.round(
            event.nativeEvent.contentOffset.x / width
          );
          setCurrentSlide(slide);
        }}
      >
        {slides.map((slide, index) => {
          const Icon = slide.icon;
          return (
            <View key={slide.id} style={[styles.slide, { width }]}>
              <View style={styles.slideContent}>
                <View
                  style={[
                    styles.iconContainer,
                    { backgroundColor: `${slide.color}20` },
                  ]}
                >
                  <Icon color={slide.color} size={64} />
                </View>

                <Text style={styles.title}>{slide.title}</Text>
                <Text style={styles.description}>{slide.description}</Text>

                {currentSlide === slides.length - 1 && (
                  <View style={styles.featuresContainer}>
                    <View style={styles.feature}>
                      <CheckCircle2
                        color={Colors.dark.success}
                        size={20}
                      />
                      <Text style={styles.featureText}>
                        Identity verification in minutes
                      </Text>
                    </View>
                    <View style={styles.feature}>
                      <CheckCircle2
                        color={Colors.dark.success}
                        size={20}
                      />
                      <Text style={styles.featureText}>
                        Link bank accounts securely
                      </Text>
                    </View>
                    <View style={styles.feature}>
                      <CheckCircle2
                        color={Colors.dark.success}
                        size={20}
                      />
                      <Text style={styles.featureText}>
                        Start with up to $300/day limit
                      </Text>
                    </View>
                  </View>
                )}
              </View>
            </View>
          );
        })}
      </ScrollView>

      <View style={styles.footer}>
        <View style={styles.pagination}>
          {slides.map((_, index) => {
            const inputRange = [
              (index - 1) * width,
              index * width,
              (index + 1) * width,
            ];

            const dotWidth = scrollX.interpolate({
              inputRange,
              outputRange: [8, 24, 8],
              extrapolate: "clamp",
            });

            const opacity = scrollX.interpolate({
              inputRange,
              outputRange: [0.3, 1, 0.3],
              extrapolate: "clamp",
            });

            return (
              <Animated.View
                key={index}
                style={[
                  styles.paginationDot,
                  { width: dotWidth, opacity },
                ]}
              />
            );
          })}
        </View>

        <TouchableOpacity
          style={styles.nextButton}
          onPress={handleNext}
        >
          <Text style={styles.nextButtonText}>
            {currentSlide === slides.length - 1
              ? "Get Started"
              : "Continue"}
          </Text>
          <ArrowRight color={Colors.dark.background} size={20} />
        </TouchableOpacity>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.dark.background,
  },
  logoContainer: {
    position: "absolute",
    top: 60,
    left: 20,
    zIndex: 10,
  },
  logo: {
    width: 140,
    height: 36,
  },
  skipButton: {
    position: "absolute",
    top: 60,
    right: 20,
    zIndex: 10,
    paddingHorizontal: 16,
    paddingVertical: 8,
  },
  skipButtonText: {
    fontSize: 14,
    fontWeight: "600" as const,
    color: Colors.dark.textSecondary,
  },
  slide: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  slideContent: {
    alignItems: "center",
    paddingHorizontal: 40,
    maxWidth: 500,
  },
  iconContainer: {
    width: 140,
    height: 140,
    borderRadius: 70,
    justifyContent: "center",
    alignItems: "center",
    marginBottom: 40,
  },
  title: {
    fontSize: 32,
    fontWeight: "800" as const,
    color: Colors.dark.text,
    marginBottom: 16,
    textAlign: "center",
    letterSpacing: -0.5,
  },
  description: {
    fontSize: 16,
    color: Colors.dark.textSecondary,
    textAlign: "center",
    lineHeight: 24,
    marginBottom: 24,
  },
  featuresContainer: {
    gap: 16,
    marginTop: 24,
    width: "100%",
  },
  feature: {
    flexDirection: "row",
    alignItems: "center",
    gap: 12,
  },
  featureText: {
    fontSize: 14,
    color: Colors.dark.text,
    fontWeight: "500" as const,
  },
  footer: {
    paddingHorizontal: 40,
    paddingBottom: 40,
    gap: 24,
  },
  pagination: {
    flexDirection: "row",
    justifyContent: "center",
    alignItems: "center",
    gap: 8,
  },
  paginationDot: {
    height: 8,
    borderRadius: 4,
    backgroundColor: Colors.dark.primary,
  },
  nextButton: {
    flexDirection: "row",
    backgroundColor: Colors.dark.primary,
    paddingVertical: 18,
    paddingHorizontal: 32,
    borderRadius: 16,
    alignItems: "center",
    justifyContent: "center",
    gap: 12,
  },
  nextButtonText: {
    fontSize: 18,
    fontWeight: "700" as const,
    color: Colors.dark.background,
  },
});
