import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  ActivityIndicator,
  Alert,
  Linking,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { router } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { AppColors, Spacing, BorderRadius, FontSizes, FontWeights } from '@/constants/theme';
import { useAuth } from '@/contexts/AuthContext';

// Stripe Checkout API
const STRIPE_API_URL = 'https://wellnuo.smartlaunchhub.com/api/stripe';

const STARTER_KIT = {
  name: 'WellNuo Starter Kit',
  price: '$249',
  priceValue: 249,
  description: 'Everything you need to start monitoring your loved ones',
  features: [
    'Motion sensor (PIR)',
    'Door/window sensor',
    'Temperature & humidity sensor',
    'WellNuo Hub',
    'Mobile app access',
    '1 year subscription included',
  ],
};

export default function PurchaseScreen() {
  const [isProcessing, setIsProcessing] = useState(false);
  const { user } = useAuth();

  const handlePurchase = async () => {
    setIsProcessing(true);

    try {
      // Create Stripe Checkout session via our API
      const response = await fetch(`${STRIPE_API_URL}/create-checkout-session`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userId: user?.user_id || 'guest',
          email: user?.email,
          beneficiaryName: 'To be configured',
          beneficiaryAddress: 'To be configured',
          includePremium: false, // Just starter kit for now
        }),
      });

      const data = await response.json();

      if (data.url) {
        // Open Stripe Checkout in browser
        const canOpen = await Linking.canOpenURL(data.url);
        if (canOpen) {
          await Linking.openURL(data.url);
          // After returning from browser, go to activate
          Alert.alert(
            'Complete Your Purchase',
            'After completing payment in the browser, tap "Continue" to activate your kit.',
            [
              {
                text: 'Continue',
                onPress: () => router.replace('/(auth)/activate'),
              },
            ]
          );
        } else {
          Alert.alert('Error', 'Could not open payment page');
        }
      } else {
        Alert.alert('Error', data.error || 'Failed to create checkout session');
      }
    } catch (error) {
      console.error('Stripe checkout error:', error);
      Alert.alert('Error', 'Failed to connect to payment service. Please try again.');
    }

    setIsProcessing(false);
  };

  const handleSkip = () => {
    // For users who already have a kit
    router.replace('/(auth)/activate');
  };

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={styles.content}>
        {/* Header */}
        <View style={styles.header}>
          <TouchableOpacity style={styles.backButton} onPress={() => router.back()}>
            <Ionicons name="arrow-back" size={24} color={AppColors.textPrimary} />
          </TouchableOpacity>
          <Text style={styles.title}>Get Started</Text>
          <View style={styles.placeholder} />
        </View>

        {/* Product Card */}
        <View style={styles.productCard}>
          <View style={styles.productIcon}>
            <Ionicons name="hardware-chip" size={48} color={AppColors.primary} />
          </View>
          <Text style={styles.productName}>{STARTER_KIT.name}</Text>
          <Text style={styles.productPrice}>{STARTER_KIT.price}</Text>
          <Text style={styles.productDescription}>{STARTER_KIT.description}</Text>

          {/* Features */}
          <View style={styles.features}>
            {STARTER_KIT.features.map((feature, index) => (
              <View key={index} style={styles.featureRow}>
                <Ionicons name="checkmark-circle" size={20} color={AppColors.success} />
                <Text style={styles.featureText}>{feature}</Text>
              </View>
            ))}
          </View>
        </View>

        {/* Security Badge */}
        <View style={styles.securityBadge}>
          <Ionicons name="shield-checkmark" size={20} color={AppColors.success} />
          <Text style={styles.securityText}>
            Secure payment powered by Stripe
          </Text>
        </View>

        {/* Test Mode Notice */}
        <View style={styles.testNotice}>
          <Ionicons name="card" size={16} color={AppColors.primary} />
          <Text style={styles.testNoticeText}>
            Test mode: Use card 4242 4242 4242 4242
          </Text>
        </View>
      </ScrollView>

      {/* Bottom Actions */}
      <View style={styles.bottomActions}>
        <TouchableOpacity
          style={[styles.purchaseButton, isProcessing && styles.buttonDisabled]}
          onPress={handlePurchase}
          disabled={isProcessing}
        >
          {isProcessing ? (
            <ActivityIndicator color={AppColors.white} />
          ) : (
            <>
              <Ionicons name="card" size={20} color={AppColors.white} />
              <Text style={styles.purchaseButtonText}>Buy Now - {STARTER_KIT.price}</Text>
            </>
          )}
        </TouchableOpacity>

        <TouchableOpacity style={styles.skipButton} onPress={handleSkip}>
          <Text style={styles.skipButtonText}>I already have a kit</Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: AppColors.background,
  },
  content: {
    padding: Spacing.lg,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginBottom: Spacing.xl,
  },
  backButton: {
    padding: Spacing.sm,
    marginLeft: -Spacing.sm,
  },
  title: {
    fontSize: FontSizes.xl,
    fontWeight: FontWeights.bold,
    color: AppColors.textPrimary,
  },
  placeholder: {
    width: 40,
  },
  productCard: {
    backgroundColor: AppColors.white,
    borderRadius: BorderRadius.xl,
    padding: Spacing.xl,
    alignItems: 'center',
    borderWidth: 2,
    borderColor: AppColors.primary,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 4 },
    shadowOpacity: 0.1,
    shadowRadius: 12,
    elevation: 5,
  },
  productIcon: {
    width: 80,
    height: 80,
    borderRadius: 40,
    backgroundColor: `${AppColors.primary}15`,
    alignItems: 'center',
    justifyContent: 'center',
    marginBottom: Spacing.lg,
  },
  productName: {
    fontSize: FontSizes['2xl'],
    fontWeight: FontWeights.bold,
    color: AppColors.textPrimary,
    textAlign: 'center',
    marginBottom: Spacing.sm,
  },
  productPrice: {
    fontSize: FontSizes['3xl'],
    fontWeight: FontWeights.bold,
    color: AppColors.primary,
    marginBottom: Spacing.sm,
  },
  productDescription: {
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
    textAlign: 'center',
    marginBottom: Spacing.xl,
  },
  features: {
    width: '100%',
    gap: Spacing.md,
  },
  featureRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: Spacing.sm,
  },
  featureText: {
    fontSize: FontSizes.base,
    color: AppColors.textPrimary,
    flex: 1,
  },
  securityBadge: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: Spacing.sm,
    marginTop: Spacing.xl,
    paddingVertical: Spacing.md,
    backgroundColor: `${AppColors.success}10`,
    borderRadius: BorderRadius.lg,
  },
  securityText: {
    fontSize: FontSizes.sm,
    color: AppColors.success,
  },
  testNotice: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: Spacing.sm,
    marginTop: Spacing.md,
    paddingVertical: Spacing.sm,
    paddingHorizontal: Spacing.md,
    backgroundColor: `${AppColors.primary}10`,
    borderRadius: BorderRadius.md,
  },
  testNoticeText: {
    fontSize: FontSizes.xs,
    color: AppColors.primary,
    fontWeight: FontWeights.medium,
  },
  bottomActions: {
    padding: Spacing.lg,
    paddingBottom: Spacing.xl,
    gap: Spacing.md,
  },
  purchaseButton: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    gap: Spacing.sm,
    backgroundColor: AppColors.primary,
    paddingVertical: Spacing.lg,
    borderRadius: BorderRadius.lg,
  },
  buttonDisabled: {
    opacity: 0.7,
  },
  purchaseButtonText: {
    fontSize: FontSizes.lg,
    fontWeight: FontWeights.semibold,
    color: AppColors.white,
  },
  skipButton: {
    alignItems: 'center',
    paddingVertical: Spacing.md,
  },
  skipButtonText: {
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
    textDecorationLine: 'underline',
  },
});
