import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  TextInput,
  ScrollView,
  ActivityIndicator,
  Alert,
} 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';

// DEV MODE: Mock activation code
const MOCK_ACTIVATION_CODE = 'WELLNUO-DEMO';

export default function ActivateScreen() {
  const [activationCode, setActivationCode] = useState('');
  const [isActivating, setIsActivating] = useState(false);
  const [step, setStep] = useState<'code' | 'beneficiary' | 'complete'>('code');
  const [beneficiaryName, setBeneficiaryName] = useState('');
  const [relationship, setRelationship] = useState('');

  const handleActivate = async () => {
    if (!activationCode.trim()) {
      Alert.alert('Error', 'Please enter activation code');
      return;
    }

    setIsActivating(true);

    // DEV MODE: Simulate activation
    await new Promise((resolve) => setTimeout(resolve, 1500));

    // Accept any code in dev mode, or use the mock code
    if (activationCode.toUpperCase() === MOCK_ACTIVATION_CODE || activationCode.length >= 6) {
      setStep('beneficiary');
    } else {
      Alert.alert('Invalid Code', 'Please check your activation code and try again.\n\nDEV: Use "WELLNUO-DEMO" or any 6+ character code.');
    }

    setIsActivating(false);
  };

  const handleAddBeneficiary = async () => {
    if (!beneficiaryName.trim()) {
      Alert.alert('Error', 'Please enter beneficiary name');
      return;
    }

    setIsActivating(true);

    // DEV MODE: Simulate adding beneficiary
    await new Promise((resolve) => setTimeout(resolve, 1000));

    setStep('complete');
    setIsActivating(false);
  };

  const handleComplete = () => {
    // Navigate to main app
    router.replace('/(tabs)');
  };

  const handleUseDemoCode = () => {
    setActivationCode(MOCK_ACTIVATION_CODE);
  };

  // Step 1: Enter activation code
  if (step === 'code') {
    return (
      <SafeAreaView style={styles.container}>
        <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
          {/* 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}>Activate Kit</Text>
            <View style={styles.placeholder} />
          </View>

          {/* Icon */}
          <View style={styles.iconContainer}>
            <Ionicons name="qr-code" size={64} color={AppColors.primary} />
          </View>

          {/* Instructions */}
          <Text style={styles.instructions}>
            Enter the activation code from your WellNuo Starter Kit packaging
          </Text>

          {/* Input */}
          <View style={styles.inputContainer}>
            <TextInput
              style={styles.input}
              value={activationCode}
              onChangeText={setActivationCode}
              placeholder="WELLNUO-XXXX-XXXX"
              placeholderTextColor={AppColors.textMuted}
              autoCapitalize="characters"
              autoCorrect={false}
            />
          </View>

          {/* Development Notice */}
          <View style={styles.devNotice}>
            <Ionicons name="construct" size={20} color={AppColors.warning} />
            <Text style={styles.devNoticeTitle}>Sensor Activation In Development</Text>
            <Text style={styles.devNoticeText}>
              Real sensor pairing is coming soon. For now, enter any code (6+ characters) to continue testing the app.
            </Text>
            <TouchableOpacity style={styles.demoCodeButton} onPress={handleUseDemoCode}>
              <Text style={styles.demoCodeButtonText}>Use Demo Code</Text>
            </TouchableOpacity>
          </View>

          {/* Activate Button */}
          <TouchableOpacity
            style={[styles.primaryButton, isActivating && styles.buttonDisabled]}
            onPress={handleActivate}
            disabled={isActivating}
          >
            {isActivating ? (
              <ActivityIndicator color={AppColors.white} />
            ) : (
              <Text style={styles.primaryButtonText}>Activate</Text>
            )}
          </TouchableOpacity>

          {/* Skip for now */}
          <TouchableOpacity style={styles.skipButton} onPress={handleComplete}>
            <Text style={styles.skipButtonText}>Skip for now</Text>
          </TouchableOpacity>
        </ScrollView>
      </SafeAreaView>
    );
  }

  // Step 2: Add beneficiary
  if (step === 'beneficiary') {
    return (
      <SafeAreaView style={styles.container}>
        <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
          {/* Header */}
          <View style={styles.header}>
            <TouchableOpacity style={styles.backButton} onPress={() => setStep('code')}>
              <Ionicons name="arrow-back" size={24} color={AppColors.textPrimary} />
            </TouchableOpacity>
            <Text style={styles.title}>Add Beneficiary</Text>
            <View style={styles.placeholder} />
          </View>

          {/* Icon */}
          <View style={styles.iconContainer}>
            <Ionicons name="person-add" size={64} color={AppColors.primary} />
          </View>

          {/* Instructions */}
          <Text style={styles.instructions}>
            Who will you be monitoring with this kit?
          </Text>

          {/* Name Input */}
          <View style={styles.inputGroup}>
            <Text style={styles.inputLabel}>Full Name</Text>
            <TextInput
              style={styles.input}
              value={beneficiaryName}
              onChangeText={setBeneficiaryName}
              placeholder="e.g., Grandma Julia"
              placeholderTextColor={AppColors.textMuted}
            />
          </View>

          {/* Relationship Input */}
          <View style={styles.inputGroup}>
            <Text style={styles.inputLabel}>Relationship (optional)</Text>
            <TextInput
              style={styles.input}
              value={relationship}
              onChangeText={setRelationship}
              placeholder="e.g., Mother, Father, Grandmother"
              placeholderTextColor={AppColors.textMuted}
            />
          </View>

          {/* Relationship Quick Select */}
          <View style={styles.quickSelect}>
            {['Mother', 'Father', 'Grandmother', 'Grandfather'].map((rel) => (
              <TouchableOpacity
                key={rel}
                style={[
                  styles.quickSelectButton,
                  relationship === rel && styles.quickSelectButtonActive,
                ]}
                onPress={() => setRelationship(rel)}
              >
                <Text
                  style={[
                    styles.quickSelectText,
                    relationship === rel && styles.quickSelectTextActive,
                  ]}
                >
                  {rel}
                </Text>
              </TouchableOpacity>
            ))}
          </View>

          {/* Continue Button */}
          <TouchableOpacity
            style={[styles.primaryButton, isActivating && styles.buttonDisabled]}
            onPress={handleAddBeneficiary}
            disabled={isActivating}
          >
            {isActivating ? (
              <ActivityIndicator color={AppColors.white} />
            ) : (
              <Text style={styles.primaryButtonText}>Continue</Text>
            )}
          </TouchableOpacity>
        </ScrollView>
      </SafeAreaView>
    );
  }

  // Step 3: Complete
  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.content}>
        {/* Success Icon */}
        <View style={styles.successContainer}>
          <View style={styles.successIcon}>
            <Ionicons name="checkmark-circle" size={80} color={AppColors.success} />
          </View>

          <Text style={styles.successTitle}>Kit Activated!</Text>
          <Text style={styles.successMessage}>
            Your WellNuo kit has been successfully activated for{' '}
            <Text style={styles.beneficiaryHighlight}>{beneficiaryName}</Text>
          </Text>

          {/* Next Steps */}
          <View style={styles.nextSteps}>
            <Text style={styles.nextStepsTitle}>Next Steps:</Text>
            <View style={styles.stepItem}>
              <Text style={styles.stepNumber}>1</Text>
              <Text style={styles.stepText}>Place sensors in your loved one's home</Text>
            </View>
            <View style={styles.stepItem}>
              <Text style={styles.stepNumber}>2</Text>
              <Text style={styles.stepText}>Connect the hub to WiFi</Text>
            </View>
            <View style={styles.stepItem}>
              <Text style={styles.stepNumber}>3</Text>
              <Text style={styles.stepText}>Start receiving activity updates</Text>
            </View>
          </View>
        </View>

        {/* Complete Button */}
        <TouchableOpacity style={styles.primaryButton} onPress={handleComplete}>
          <Text style={styles.primaryButtonText}>Go to Dashboard</Text>
        </TouchableOpacity>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: AppColors.background,
  },
  content: {
    flex: 1,
    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,
  },
  iconContainer: {
    alignItems: 'center',
    marginBottom: Spacing.xl,
  },
  instructions: {
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
    textAlign: 'center',
    marginBottom: Spacing.xl,
    lineHeight: 24,
  },
  inputContainer: {
    marginBottom: Spacing.lg,
  },
  inputGroup: {
    marginBottom: Spacing.lg,
  },
  inputLabel: {
    fontSize: FontSizes.sm,
    fontWeight: FontWeights.medium,
    color: AppColors.textPrimary,
    marginBottom: Spacing.sm,
  },
  input: {
    backgroundColor: AppColors.surface,
    borderRadius: BorderRadius.lg,
    paddingHorizontal: Spacing.lg,
    paddingVertical: Spacing.md,
    fontSize: FontSizes.lg,
    color: AppColors.textPrimary,
    textAlign: 'center',
    borderWidth: 1,
    borderColor: AppColors.border,
  },
  devNotice: {
    alignItems: 'center',
    marginBottom: Spacing.xl,
    paddingVertical: Spacing.lg,
    paddingHorizontal: Spacing.lg,
    backgroundColor: `${AppColors.warning}10`,
    borderRadius: BorderRadius.lg,
    borderWidth: 1,
    borderColor: `${AppColors.warning}30`,
  },
  devNoticeTitle: {
    fontSize: FontSizes.base,
    fontWeight: FontWeights.semibold,
    color: AppColors.warning,
    marginTop: Spacing.sm,
    marginBottom: Spacing.sm,
  },
  devNoticeText: {
    fontSize: FontSizes.sm,
    color: AppColors.textSecondary,
    textAlign: 'center',
    lineHeight: 20,
    marginBottom: Spacing.md,
  },
  demoCodeButton: {
    paddingVertical: Spacing.sm,
    paddingHorizontal: Spacing.lg,
    backgroundColor: AppColors.warning,
    borderRadius: BorderRadius.md,
  },
  demoCodeButtonText: {
    fontSize: FontSizes.sm,
    fontWeight: FontWeights.medium,
    color: AppColors.white,
  },
  primaryButton: {
    backgroundColor: AppColors.primary,
    paddingVertical: Spacing.lg,
    borderRadius: BorderRadius.lg,
    alignItems: 'center',
    marginTop: Spacing.md,
  },
  buttonDisabled: {
    opacity: 0.7,
  },
  primaryButtonText: {
    fontSize: FontSizes.lg,
    fontWeight: FontWeights.semibold,
    color: AppColors.white,
  },
  skipButton: {
    alignItems: 'center',
    paddingVertical: Spacing.lg,
  },
  skipButtonText: {
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
    textDecorationLine: 'underline',
  },
  quickSelect: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: Spacing.sm,
    marginBottom: Spacing.xl,
  },
  quickSelectButton: {
    paddingHorizontal: Spacing.md,
    paddingVertical: Spacing.sm,
    borderRadius: BorderRadius.full,
    backgroundColor: AppColors.surface,
    borderWidth: 1,
    borderColor: AppColors.border,
  },
  quickSelectButtonActive: {
    backgroundColor: AppColors.primary,
    borderColor: AppColors.primary,
  },
  quickSelectText: {
    fontSize: FontSizes.sm,
    color: AppColors.textSecondary,
  },
  quickSelectTextActive: {
    color: AppColors.white,
    fontWeight: FontWeights.medium,
  },
  successContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  successIcon: {
    marginBottom: Spacing.xl,
  },
  successTitle: {
    fontSize: FontSizes['2xl'],
    fontWeight: FontWeights.bold,
    color: AppColors.textPrimary,
    marginBottom: Spacing.md,
  },
  successMessage: {
    fontSize: FontSizes.base,
    color: AppColors.textSecondary,
    textAlign: 'center',
    marginBottom: Spacing.xxl,
  },
  beneficiaryHighlight: {
    fontWeight: FontWeights.bold,
    color: AppColors.primary,
  },
  nextSteps: {
    width: '100%',
    backgroundColor: AppColors.surface,
    borderRadius: BorderRadius.lg,
    padding: Spacing.lg,
  },
  nextStepsTitle: {
    fontSize: FontSizes.base,
    fontWeight: FontWeights.semibold,
    color: AppColors.textPrimary,
    marginBottom: Spacing.md,
  },
  stepItem: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: Spacing.md,
    marginBottom: Spacing.sm,
  },
  stepNumber: {
    width: 24,
    height: 24,
    borderRadius: 12,
    backgroundColor: AppColors.primary,
    color: AppColors.white,
    textAlign: 'center',
    lineHeight: 24,
    fontSize: FontSizes.sm,
    fontWeight: FontWeights.bold,
    overflow: 'hidden',
  },
  stepText: {
    fontSize: FontSizes.sm,
    color: AppColors.textSecondary,
    flex: 1,
  },
});
