import React, { useRef, useState } from 'react';
import type { ReactNode } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {
  View,
  Text,
  Image,
  TouchableOpacity,
  FlatList,
  Dimensions,
  NativeSyntheticEvent,
  NativeScrollEvent,
  type ImageSourcePropType,
} from 'react-native'
import { useRouter } from 'expo-router';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { useTheme } from '@/constants/ThemeContext';
import { useLanguage } from '@/i18n/LanguageContext';
import { markOnboardingCompleted } from '@/services/storage/onboardingStorage';
import {
  onboardingStyles,
  onboardingTheme,
} from '@/styles/onboarding.styles';
import { WelcomeScreen } from '@/components/WelcomeScreen';
import {
  Bus,
  Camera,
  QrCode,
  ArrowRight,
  ArrowLeft,
  Sparkles,
  CheckCircle2,
} from 'lucide-react-native';

const { width: SCREEN_WIDTH } = Dimensions.get('window');

interface SlideItem {
  id: number;
  icon?: ReactNode;
  tag: string;
  title: string;
  description: string;
  highlights?: string[];
  image: ImageSourcePropType;
  isWelcomeScreen?: boolean;
}

export default function OnboardingScreen() {
  const router = useRouter();
  const insets = useSafeAreaInsets();
  const { isDark } = useTheme();
  const { t } = useLanguage();

  const [currentIndex, setCurrentIndex] = useState(0);
  const flatListRef = useRef<FlatList<SlideItem>>(null);

  const slides: SlideItem[] = [
    {
      id: 0,
      icon: (
        <Bus
          size={20}
          color={onboardingTheme.colors.skyAccent}
        />
      ),
      tag: 'CAMEROON PREMIUM TRANSIT',
      title: t('slide1Title'),
      description: t('slide1Desc'),
      highlights: [
        'Douala ➔ Yaoundé ➔ Bafoussam ➔ Kribi routes',
        'VIP luxury buses with guaranteed seat selection',
        'Live departure schedules & seat availability',
      ],
      image: require('@/assets/images/onboarding_bus_travel.png'),
    },
    {
      id: 1,
      icon: (
        <Camera
          size={20}
          color={onboardingTheme.colors.skyAccent}
        />
      ),
      tag: 'AI LIVE CAMERA & SAFETY',
      title: t('slide2Title'),
      description: t('slide2Desc'),
      highlights: [
        'Onboard AI camera surveillance on all trips',
        'Real-time GPS tracking & trip status updates',
        'Enhanced safety & peace of mind for travelers',
      ],
      image: require('@/assets/images/onboarding_live_camera.png'),
    },
    {
      id: 2,
      icon: (
        <QrCode
          size={20}
          color={onboardingTheme.colors.skyAccent}
        />
      ),
      tag: 'INSTANT E-TICKET BOARDING',
      title: t('slide3Title'),
      description: t('slide3Desc'),
      highlights: [
        'Digital boarding pass stored on your mobile phone',
        'Instant mobile money checkout (MTN & Orange)',
        'Scan QR code at bus terminal boarding gates',
      ],
      image: require('@/assets/images/onboarding_digital_ticket.png'),
    },
    {
      id: 3,
      isWelcomeScreen: true,
      tag: 'WELCOME TO TRAVELCAM',
      title: 'Ready for a Smarter Travel Experience?',
      description:
        'Explore inter-city routes or sign in to access your digital tickets.',
      image: require('@/assets/images/onboarding_bus_travel.png'),
    },
  ];

  // Persist onboarding state before navigating.
  const handleGetStarted = async () => {
    try {
      await markOnboardingCompleted();
      await AsyncStorage.setItem('@travelcam_guest_mode', 'true');
      router.replace('/(tabs)' as any);
    } catch (error) {
      console.error('Failed to continue as guest:', error);
    }
  };

  const handleSignIn = async () => {
    try {
      await markOnboardingCompleted();
      await AsyncStorage.removeItem('@travelcam_guest_mode');
      router.push('/(auth)/login' as any);
    } catch (error) {
      console.error('Failed to open sign-in:', error);
    }
  };

  const handleSignUp = async () => {
    try {
      await markOnboardingCompleted();
      await AsyncStorage.removeItem('@travelcam_guest_mode');
      router.push('/(auth)/register' as any);
    } catch (error) {
      console.error('Failed to open registration:', error);
    }
  };

  const handleScroll = (
    event: NativeSyntheticEvent<NativeScrollEvent>
  ) => {
    const offsetX = event.nativeEvent.contentOffset.x;
    const index = Math.round(offsetX / SCREEN_WIDTH);

    if (index >= 0 && index < slides.length) {
      setCurrentIndex((previousIndex) =>
        previousIndex === index ? previousIndex : index
      );
    }
  };

  const goToStep = (index: number) => {
    if (index < 0 || index >= slides.length) {
      return;
    }

    flatListRef.current?.scrollToIndex({
      index,
      animated: true,
    });

    setCurrentIndex(index);
  };

  const goToNextStep = () => {
    if (currentIndex < slides.length - 1) {
      goToStep(currentIndex + 1);
    }
  };

  const goToPrevStep = () => {
    if (currentIndex > 0) {
      goToStep(currentIndex - 1);
    }
  };

  return (
    <View
      style={[
        onboardingStyles.root,
        {
          backgroundColor: isDark
            ? onboardingTheme.colors.navyDark
            : onboardingTheme.colors.lightBg,
          paddingTop: Math.max(insets.top, 12),
          paddingBottom: Math.max(insets.bottom, 12),
        },
      ]}
    >
      <FlatList<SlideItem>
        ref={flatListRef}
        data={slides}
        keyExtractor={(item) => item.id.toString()}
        horizontal
        pagingEnabled
        showsHorizontalScrollIndicator={false}
        onScroll={handleScroll}
        scrollEventThrottle={16}
        getItemLayout={(_, index) => ({
          length: SCREEN_WIDTH,
          offset: SCREEN_WIDTH * index,
          index,
        })}
        renderItem={({ item, index }) => (
          <View
            style={[
              onboardingStyles.slideWrapper,
              { width: SCREEN_WIDTH },
            ]}
          >
            {!item.isWelcomeScreen ? (
              <View style={onboardingStyles.slideContent}>
                {/* Hero illustration */}
                <View style={onboardingStyles.heroBox}>
                  <Image
                    source={item.image}
                    style={onboardingStyles.heroImage}
                    resizeMode="cover"
                  />

                  <View style={onboardingStyles.tagBadge}>
                    <Sparkles
                      size={11}
                      color={onboardingTheme.colors.skyAccent}
                    />
                    <Text style={onboardingStyles.tagText}>
                      {item.tag}
                    </Text>
                  </View>
                </View>

                {/* Feature card */}
                <View
                  style={
                    isDark
                      ? onboardingStyles.cardDark
                      : onboardingStyles.cardLight
                  }
                >
                  <View>
                    <View style={onboardingStyles.badgeRow}>
                      <View style={onboardingStyles.iconBox}>
                        {item.icon}
                      </View>

                      <Text style={onboardingStyles.badgeText}>
                        Feature {index + 1} of 3
                      </Text>
                    </View>

                    <Text
                      style={
                        isDark
                          ? onboardingStyles.titleDark
                          : onboardingStyles.titleLight
                      }
                    >
                      {item.title}
                    </Text>

                    <Text
                      style={
                        isDark
                          ? onboardingStyles.descriptionDark
                          : onboardingStyles.descriptionLight
                      }
                    >
                      {item.description}
                    </Text>
                  </View>

                  <View
                    style={
                      isDark
                        ? onboardingStyles.highlightsBoxDark
                        : onboardingStyles.highlightsBoxLight
                    }
                  >
                    {item.highlights?.map((point, pointIndex) => (
                      <View
                        key={`${item.id}-${pointIndex}`}
                        style={onboardingStyles.highlightRow}
                      >
                        <CheckCircle2
                          size={13}
                          color={onboardingTheme.colors.skyAccent}
                        />

                        <Text
                          style={
                            isDark
                              ? onboardingStyles.highlightTextDark
                              : onboardingStyles.highlightTextLight
                          }
                        >
                          {point}
                        </Text>
                      </View>
                    ))}
                  </View>
                </View>
              </View>
            ) : (
              <WelcomeScreen
                onGetStarted={handleGetStarted}
                onLogin={handleSignIn}
                onRegister={handleSignUp}
              />
            )}
          </View>
        )}
      />

      {/* Bottom navigation */}
      {currentIndex < 3 && (
        <View style={onboardingStyles.bottomBar}>
          {currentIndex > 0 ? (
            <TouchableOpacity
              onPress={goToPrevStep}
              accessibilityRole="button"
              accessibilityLabel={t('back')}
              style={
                isDark
                  ? onboardingStyles.btnSecondaryDark
                  : onboardingStyles.btnSecondaryLight
              }
            >
              <ArrowLeft
                size={16}
                color={
                  isDark
                    ? onboardingTheme.colors.skyAccent
                    : onboardingTheme.colors.navyPrimary
                }
              />

              <Text
                style={
                  isDark
                    ? onboardingStyles.btnSecondaryTextDark
                    : onboardingStyles.btnSecondaryTextLight
                }
              >
                {t('back')}
              </Text>
            </TouchableOpacity>
          ) : (
            <View style={onboardingStyles.emptyPlaceholder} />
          )}

          <View style={onboardingStyles.dotsRow}>
            {slides.map((slide, index) => (
              <TouchableOpacity
                key={slide.id}
                onPress={() => goToStep(index)}
                accessibilityRole="button"
                accessibilityLabel={`Go to onboarding slide ${index + 1}`}
                accessibilityState={{
                  selected: currentIndex === index,
                }}
                style={
                  currentIndex === index
                    ? onboardingStyles.dotActive
                    : isDark
                    ? onboardingStyles.dotInactiveDark
                    : onboardingStyles.dotInactiveLight
                }
              />
            ))}
          </View>

          <TouchableOpacity
            onPress={goToNextStep}
            accessibilityRole="button"
            accessibilityLabel={t('onboardingNext')}
            style={onboardingStyles.btnPrimary}
          >
            <Text style={onboardingStyles.btnPrimaryText}>
              {t('onboardingNext')}
            </Text>

            <ArrowRight
              size={16}
              color={onboardingTheme.colors.navyPrimary}
            />
          </TouchableOpacity>
        </View>
      )}
    </View>
  );
}