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 { CompositeNavigationProp, useNavigation } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { AuthStackParamList, RootStackParamList } from '@navigation/navigationTypes';
import { RouteNames } from '@utils/constants';
import { getStyles } from './OtpScreen.styles';
import { RootState, useAppDispatch, useAppSelector, verifyOtp } from '@store';

export const OtpScreen: React.FC<{ route: any }> = ({ route }) => {
  const { colors } = useAppTheme();
  const styles = getStyles(colors);
  const navigation = useNavigation<
    CompositeNavigationProp<
      NativeStackNavigationProp<AuthStackParamList, RouteNames.Otp>,
      NativeStackNavigationProp<RootStackParamList>
    >
  >();

  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);
  const dispatch = useAppDispatch();
  const { loading } = useAppSelector((state: RootState) => state.auth);

  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 = async () => {
    if (otp.length < 6) {
      setError(true);
      Alert.alert('Invalid OTP', 'Please enter a 6-digit verification code.');
      return;
    }
    try {
      await dispatch(
        verifyOtp({ phone, code: otp, role: 'DELIVERY' }),
      ).unwrap();
      navigation.navigate('OnBoarding', { screen: RouteNames.CompleteProfile });
    } catch (error) {
      Alert.alert('Error', error as string);
    }
  };

  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={loading}
            style={styles.verifyButton}
          />
        </View>

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

export default OtpScreen;
