import React, { useState, useEffect } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Alert } from 'react-native';
import { OtpInput, NumericKeypad, PrimaryButton } from '@components';
import { useAppTheme } from '@theme';
import { useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { AuthStackParamList } from '@navigation/navigationTypes';
import { RouteNames } from '@utils/constants';
import { getStyles } from './OtpScreen.styles';

export const OtpScreen: React.FC<{ route: any }> = ({ route }) => {
  const { colors } = useAppTheme();
  const styles = getStyles(colors);
  const navigation = useNavigation<NativeStackNavigationProp<AuthStackParamList>>();
  
  const phone = route?.params?.phone || '+91 98765 43210';
  const [otp, setOtp] = useState('');
  const [timer, setTimer] = useState(30);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(false);

  useEffect(() => {
    if (timer <= 0) return;
    const interval = setInterval(() => {
      setTimer((prev) => prev - 1);
    }, 1000);
    return () => clearInterval(interval);
  }, [timer]);

  const handleKeyPress = (digit: string) => {
    if (otp.length < 6) {
      setError(false);
      setOtp((prev) => prev + digit);
    }
  };

  const handleBackspace = () => {
    setOtp((prev) => prev.slice(0, -1));
  };

  const handleVerify = () => {
    if (otp.length < 6) {
      setError(true);
      Alert.alert('Invalid OTP', 'Please enter a 6-digit verification code.');
      return;
    }
    
    setIsLoading(true);
    setTimeout(() => {
      setIsLoading(false);
      if (otp === '123456' || otp.length === 6) {
        navigation.navigate(RouteNames.SetLocation);
      } else {
        setError(true);
        Alert.alert('Verification Failed', 'The code you entered is incorrect. Try 123456.');
      }
    }, 1200);
  };

  const handleResend = () => {
    if (timer > 0) return;
    setOtp('');
    setTimer(30);
    Alert.alert('OTP Resent', 'A new verification code has been sent to your mobile number.');
  };

  return (
    <View style={styles.container}>
      <ScrollView contentContainerStyle={styles.scrollContainer} bounces={false}>
        <View style={styles.headerContainer}>
          <Text style={styles.title}>Verify Phone</Text>
          <Text style={styles.subtitle}>
            Enter the 6-digit OTP code sent to{' '}
            <Text style={styles.phoneText}>{phone}</Text>
          </Text>
        </View>

        <View style={styles.contentWrapper}>
          <View style={styles.otpWrapper}>
            <OtpInput length={6} value={otp} error={error} />
          </View>

          <View style={styles.resendContainer}>
            {timer > 0 ? (
              <Text style={styles.resendText}>
                Resend code in <Text style={{ color: colors.primary, fontWeight: 'bold' }}>00:{timer < 10 ? `0${timer}` : timer}</Text>
              </Text>
            ) : (
              <TouchableOpacity onPress={handleResend} activeOpacity={0.7}>
                <Text style={styles.resendLink}>Resend Code</Text>
              </TouchableOpacity>
            )}
          </View>

          <PrimaryButton
            title="Verify & Continue"
            onPress={handleVerify}
            isLoading={isLoading}
            style={styles.verifyButton}
          />
        </View>

        <View style={styles.keypadContainer}>
          <NumericKeypad
            onPress={handleKeyPress}
            onBackspace={handleBackspace}
            disabled={isLoading}
          />
        </View>
      </ScrollView>
    </View>
  );
};

export default OtpScreen;
