import React, { useEffect, useState, useCallback } from 'react';
import { View, Text, ScrollView, Pressable, ActivityIndicator, Alert } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { PAYWALL_RESULT } from 'react-native-purchases-ui';

import { Button, ButtonText } from '@/components/ui/button';
import { colors, typography, shadow, radius } from '@/constants/theme';
import { RewardedAdModal } from '@/components/RewardedAdModal';
import { presentProPaywall, restoreProPurchases } from '@/lib/revenuecat';

/**
 * Paywall Screen (US-6 & US-7)
 * 03-DESIGN-SYSTEM-AND-SCREENS.md §5.7 & 02-ARCHITECTURE-AND-DATA.md §11.3
 *
 * Calls RevenueCatUI.presentPaywallIfNeeded({ requiredEntitlementIdentifier: 'pro' }).
 * Renders the secondary "watch an ad for 1 bonus session" offer (PRD US-7) after paywall dismiss.
 */
export default function PaywallScreen() {
  const router = useRouter();
  const [isProcessing, setIsProcessing] = useState<boolean>(true);
  const [paywallDismissed, setPaywallDismissed] = useState<boolean>(false);
  const [adLoading, setAdLoading] = useState<boolean>(false);

  const triggerPaywall = useCallback(async () => {
    setIsProcessing(true);
    try {
      const { purchased, result } = await presentProPaywall();

      if (purchased) {
        // Successful purchase/restore immediately unlocks unlimited sessions (US-6 AC3)
        router.back();
        return;
      }

      // User dismissed without purchasing or cancelled
      setPaywallDismissed(true);
    } catch (error) {
      console.error('[Paywall] Failed to present paywall:', error);
      setPaywallDismissed(true);
    } finally {
      setIsProcessing(false);
    }
  }, [router]);

  useEffect(() => {
    triggerPaywall();
  }, [triggerPaywall]);

  const [isAdModalVisible, setIsAdModalVisible] = useState<boolean>(false);

  const handleWatchAdBonus = () => {
    setIsAdModalVisible(true);
  };

  // Both handlers below are memoized on purpose. RewardedAdModal derives its
  // ad-loading effect from these props, so a fresh closure on every render of
  // this screen would tear down the live ad listeners and restart the request
  // mid-playback. Stable identities keep an in-flight ad intact.
  const handleAdModalClose = useCallback(() => {
    setIsAdModalVisible(false);
  }, []);

  const handleAdRewardEarned = useCallback(() => {
    setIsAdModalVisible(false);
    Alert.alert(
      'Bonus Round Unlocked!',
      'You have earned 1 additional practice scenario round. Go ahead and start your conversation.',
      [{ text: 'Start Practicing', onPress: () => router.back() }]
    );
  }, [router]);

  const handleRestore = async () => {
    setIsProcessing(true);
    try {
      const isPro = await restoreProPurchases();
      if (isPro) {
        Alert.alert('Purchases Restored', 'Your Pro subscription is active. Unlimited practice is unlocked!', [
          { text: 'Continue', onPress: () => router.back() },
        ]);
      } else {
        Alert.alert('No Subscription Found', 'We could not find an active Pro subscription for this account.');
      }
    } catch (err) {
      Alert.alert('Restore Failed', 'Unable to restore purchases at this time. Please try again.');
    } finally {
      setIsProcessing(false);
    }
  };

  if (isProcessing) {
    return (
      <SafeAreaView style={{ flex: 1, backgroundColor: colors.background }}>
        <View className="flex-1 items-center justify-center px-8">
          <ActivityIndicator size="large" color={colors.primary} />
          <Text
            style={{
              fontFamily: typography.body.fontFamily,
              fontSize: 15,
              color: colors.textSecondary,
              marginTop: 16,
              textAlign: 'center',
            }}
          >
            Connecting to Store...
          </Text>
        </View>
      </SafeAreaView>
    );
  }

  // ─── Secondary Fallback UI (§5.7: shown after RevenueCat paywall dismiss) ───
  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: colors.background }}>
      <ScrollView
        className="flex-1 px-5"
        contentContainerStyle={{ flexGrow: 1, paddingBottom: 40 }}
        showsVerticalScrollIndicator={false}
      >
        {/* Close Button Header */}
        <View className="flex-row justify-end pt-2 pb-4">
          <Pressable
            onPress={() => router.replace('/(tabs)/home')}
            hitSlop={{ top: 12, bottom: 12, left: 12, right: 12 }}
            accessibilityRole="button"
            accessibilityLabel="Close and return home"
            style={{
              width: 36,
              height: 36,
              borderRadius: 18,
              backgroundColor: 'rgba(0,0,0,0.05)',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <Ionicons name="close" size={22} color={colors.textPrimary} />
          </Pressable>
        </View>

        {/* Main Gating Message */}
        <View className="items-center text-center mb-6">
          <View
            style={{
              width: 60,
              height: 60,
              borderRadius: 30,
              backgroundColor: 'rgba(224, 122, 95, 0.12)',
              alignItems: 'center',
              justifyContent: 'center',
              marginBottom: 16,
            }}
          >
            <Ionicons name="sparkles" size={28} color={colors.accent} />
          </View>

          <Text
            style={{
              fontFamily: typography.h1.fontFamily,
              fontSize: 24,
              lineHeight: 30,
              color: colors.textPrimary,
              textAlign: 'center',
              marginBottom: 8,
            }}
          >
            Free Rounds Used
          </Text>

          <Text
            style={{
              fontFamily: typography.body.fontFamily,
              fontSize: 15,
              lineHeight: 22,
              color: colors.textSecondary,
              textAlign: 'center',
            }}
          >
            You have completed your 3 free practice rounds. Unlock unlimited roleplay conversations to master charge-nurse communication.
          </Text>
        </View>

        {/* Primary CTA: Re-open Paywall */}
        <Button
          size="lg"
          onPress={triggerPaywall}
          accessibilityRole="button"
          accessibilityLabel="Subscribe for unlimited practice"
          style={{
            minHeight: 52,
            borderRadius: radius.pill,
            backgroundColor: colors.primary,
            marginBottom: 20,
          }}
        >
          <ButtonText
            style={{
              fontFamily: typography.bodyBold.fontFamily,
              fontSize: 16,
              color: '#FFFFFF',
            }}
          >
            Unlock Unlimited Practice
          </ButtonText>
        </Button>

        {/* Secondary Offer Card (PRD US-7 & §5.7: Watch ad for 1 bonus session) */}
        <View
          style={[
            {
              backgroundColor: colors.surface,
              borderRadius: radius.lg,
              padding: 18,
              borderWidth: 1,
              borderColor: colors.border,
              marginBottom: 24,
            },
            shadow.card,
          ]}
        >
          <View className="flex-row items-center mb-2">
            <Ionicons name="play-circle-outline" size={22} color={colors.accent} style={{ marginRight: 8 }} />
            <Text
              style={{
                fontFamily: typography.bodyBold.fontFamily,
                fontSize: 16,
                color: colors.textPrimary,
              }}
            >
              Need One More Round?
            </Text>
          </View>

          <Text
            style={{
              fontFamily: typography.caption.fontFamily,
              fontSize: 13,
              lineHeight: 18,
              color: colors.textSecondary,
              marginBottom: 14,
            }}
          >
            Watch a quick sponsor message to earn 1 additional practice scenario session today.
          </Text>

          <Button
            size="default"
            onPress={handleWatchAdBonus}
            disabled={adLoading}
            accessibilityRole="button"
            accessibilityLabel="Watch ad for 1 bonus practice session"
            style={{
              borderRadius: radius.pill,
              backgroundColor: 'rgba(224, 122, 95, 0.12)',
              borderWidth: 1,
              borderColor: colors.accent,
            }}
          >
            {adLoading ? (
              <ActivityIndicator size="small" color={colors.accent} />
            ) : (
              <ButtonText
                style={{
                  fontFamily: typography.bodyBold.fontFamily,
                  fontSize: 14,
                  color: colors.accent,
                }}
              >
                Watch Ad for 1 Bonus Session
              </ButtonText>
            )}
          </Button>
        </View>

        {/* Restore Purchases Link */}
        <View className="items-center mt-auto">
          <Pressable
            onPress={handleRestore}
            hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
            accessibilityRole="button"
            accessibilityLabel="Restore existing purchases"
          >
            <Text
              style={{
                fontFamily: typography.caption.fontFamily,
                fontSize: 13,
                color: colors.textSecondary,
                textDecorationLine: 'underline',
              }}
            >
              Already subscribed? Restore purchases
            </Text>
          </Pressable>
        </View>
      </ScrollView>

      {/* Rewarded Ad Player (Catvertising US-7) */}
      <RewardedAdModal
        visible={isAdModalVisible}
        onClose={handleAdModalClose}
        onRewardEarned={handleAdRewardEarned}
      />
    </SafeAreaView>
  );
}
