import React, { useEffect, useState } from 'react';
import { StyleSheet, Text, View, Button, TextInput, Platform, ActivityIndicator } from 'react-native';
import OtpRetriever, { OtpRetrieverEvents } from 'expo-otp-retriever';

export default function App() {
  const [otp, setOtp] = useState<string>('');
  const [manualOtp, setManualOtp] = useState<string>('');
  const [appHash, setAppHash] = useState<string>('');
  const [isListening, setIsListening] = useState<boolean>(false);
  const [status, setStatus] = useState<string>('idle');
  const [error, setError] = useState<string | null>(null);
  const [timeLeft, setTimeLeft] = useState<number>(0);

  useEffect(() => {
    // Get the app hash when the component mounts
    if (Platform.OS === 'android') {
      getAppHash();
    }

    return () => {
      // Clean up the listener when the component unmounts
      if (Platform.OS === 'android') {
        stopListening();
      }
    };
  }, []);

  useEffect(() => {
    // Countdown timer for OTP listening
    let interval: NodeJS.Timeout | null = null;
    
    if (isListening && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft((prevTime) => prevTime - 1);
      }, 1000);
    } else if (timeLeft === 0 && isListening) {
      setIsListening(false);
      setStatus('timeout');
    }

    return () => {
      if (interval) clearInterval(interval);
    };
  }, [isListening, timeLeft]);

  const getAppHash = async () => {
    try {
      const hash = await OtpRetriever.getAppHash();
      setAppHash(hash);
      setError(null);
    } catch (err: any) {
      setError(`Failed to get app hash: ${err.message}`);
    }
  };

  const startListening = async () => {
    if (Platform.OS !== 'android') {
      setError('OTP Retriever is only supported on Android');
      return;
    }

    try {
      // Set up event listeners
      const otpReceivedSubscription = OtpRetriever.addListener(
        OtpRetrieverEvents.OTP_RECEIVED,
        (event) => {
          setOtp(event.otp);
          setStatus('received');
          setIsListening(false);
        }
      );

      const otpTimeoutSubscription = OtpRetriever.addListener(
        OtpRetrieverEvents.OTP_TIMEOUT,
        () => {
          setStatus('timeout');
          setIsListening(false);
        }
      );

      const otpErrorSubscription = OtpRetriever.addListener(
        OtpRetrieverEvents.OTP_ERROR,
        (event) => {
          setError(`Error: ${event.message}`);
          setStatus('error');
          setIsListening(false);
        }
      );

      // Start listening with a 60 second timeout
      await OtpRetriever.startListener(60);
      setIsListening(true);
      setStatus('listening');
      setTimeLeft(60);
      setError(null);

      // Clean up function to remove listeners
      return () => {
        otpReceivedSubscription.remove();
        otpTimeoutSubscription.remove();
        otpErrorSubscription.remove();
      };
    } catch (err: any) {
      setError(`Failed to start OTP listener: ${err.message}`);
    }
  };

  const stopListening = async () => {
    if (Platform.OS !== 'android') return;

    try {
      await OtpRetriever.stopListener();
      setIsListening(false);
      setStatus('stopped');
    } catch (err: any) {
      setError(`Failed to stop OTP listener: ${err.message}`);
    }
  };

  const verifyOtp = () => {
    // In a real app, you would validate the OTP against your backend
    const otpToVerify = otp || manualOtp;
    
    if (otpToVerify.length < 4) {
      setError('Please enter a valid OTP code');
      return;
    }
    
    // Simulate verification
    setStatus('verifying');
    setTimeout(() => {
      setStatus('verified');
    }, 1500);
  };

  const resetDemo = () => {
    setOtp('');
    setManualOtp('');
    setStatus('idle');
    setError(null);
    setIsListening(false);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>OTP Retriever Demo</Text>
      
      {Platform.OS !== 'android' ? (
        <Text style={styles.warning}>
          This feature is only available on Android devices
        </Text>
      ) : (
        <>
          <View style={styles.hashContainer}>
            <Text style={styles.label}>App Hash:</Text>
            <Text style={styles.hash} numberOfLines={1} ellipsizeMode="middle">
              {appHash || 'Loading...'}
            </Text>
            <Text style={styles.instruction}>
              Include this hash in your SMS message for automatic detection
            </Text>
          </View>

          <View style={styles.statusContainer}>
            <Text style={styles.label}>Status:</Text>
            <Text style={[styles.status, getStatusStyle(status)]}>
              {getStatusText(status)}
              {isListening && timeLeft > 0 && ` (${timeLeft}s)`}
            </Text>
          </View>

          {error && <Text style={styles.error}>{error}</Text>}

          {otp ? (
            <View style={styles.otpContainer}>
              <Text style={styles.label}>Detected OTP:</Text>
              <Text style={styles.otpCode}>{otp}</Text>
            </View>
          ) : (
            <View style={styles.inputContainer}>
              <Text style={styles.label}>Enter OTP manually:</Text>
              <TextInput
                style={styles.input}
                value={manualOtp}
                onChangeText={setManualOtp}
                placeholder="Enter OTP"
                keyboardType="number-pad"
                maxLength={6}
                editable={!isListening}
              />
            </View>
          )}

          {status === 'verifying' ? (
            <View style={styles.buttonContainer}>
              <ActivityIndicator size="small" color="#0080FF" />
              <Text style={styles.verifyingText}>Verifying...</Text>
            </View>
          ) : status === 'verified' ? (
            <View style={styles.verifiedContainer}>
              <Text style={styles.verifiedText}>OTP Verified Successfully!</Text>
              <Button title="Start New Demo" onPress={resetDemo} />
            </View>
          ) : (
            <View style={styles.buttonContainer}>
              {!isListening && status !== 'received' && (
                <Button
                  title="Start Listening for OTP"
                  onPress={startListening}
                  disabled={isListening}
                />
              )}
              
              {isListening && (
                <Button
                  title="Stop Listening"
                  onPress={stopListening}
                  color="#FF3B30"
                />
              )}
              
              {(otp || manualOtp) && !isListening && status !== 'verified' && (
                <Button
                  title="Verify OTP"
                  onPress={verifyOtp}
                  color="#34C759"
                />
              )}
            </View>
          )}
        </>
      )}
    </View>
  );
}

// Helper functions
const getStatusText = (status: string): string => {
  switch (status) {
    case 'idle': return 'Ready to detect OTP';
    case 'listening': return 'Listening for OTP SMS';
    case 'received': return 'OTP Received';
    case 'timeout': return 'Listening Timed Out';
    case 'stopped': return 'Listening Stopped';
    case 'error': return 'Error Occurred';
    case 'verifying': return 'Verifying OTP';
    case 'verified': return 'OTP Verified';
    default: return status;
  }
};

const getStatusStyle = (status: string) => {
  switch (status) {
    case 'listening': return styles.statusListening;
    case 'received': return styles.statusSuccess;
    case 'timeout': case 'error': return styles.statusError;
    case 'verified': return styles.statusSuccess;
    default: return {};
  }
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    padding: 20,
    justifyContent: 'center',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 24,
    textAlign: 'center',
  },
  warning: {
    color: '#FF3B30',
    textAlign: 'center',
    marginVertical: 20,
    fontSize: 16,
  },
  hashContainer: {
    backgroundColor: '#F2F2F7',
    padding: 16,
    borderRadius: 8,
    marginBottom: 20,
  },
  label: {
    fontSize: 16,
    fontWeight: '600',
    marginBottom: 8,
  },
  hash: {
    fontFamily: 'monospace',
    fontSize: 14,
    padding: 8,
    backgroundColor: '#E9E9EB',
    borderRadius: 4,
  },
  instruction: {
    fontSize: 12,
    color: '#8E8E93',
    marginTop: 8,
  },
  statusContainer: {
    marginBottom: 20,
  },
  status: {
    fontSize: 16,
    fontWeight: '500',
  },
  statusListening: {
    color: '#0080FF',
  },
  statusSuccess: {
    color: '#34C759',
  },
  statusError: {
    color: '#FF3B30',
  },
  error: {
    color: '#FF3B30',
    marginBottom: 16,
  },
  otpContainer: {
    marginBottom: 20,
  },
  otpCode: {
    fontSize: 32,
    fontWeight: 'bold',
    letterSpacing: 8,
    textAlign: 'center',
    color: '#0080FF',
  },
  inputContainer: {
    marginBottom: 20,
  },
  input: {
    borderWidth: 1,
    borderColor: '#CCCCCC',
    borderRadius: 8,
    padding: 12,
    fontSize: 18,
    textAlign: 'center',
    letterSpacing: 4,
  },
  buttonContainer: {
    marginTop: 8,
    flexDirection: 'column',
    justifyContent: 'center',
    gap: 16,
  },
  verifyingText: {
    textAlign: 'center',
    marginTop: 8,
    color: '#0080FF',
  },
  verifiedContainer: {
    alignItems: 'center',
    marginTop: 16,
    gap: 16,
  },
  verifiedText: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#34C759',
    marginBottom: 8,
  },
});