import React, { useState } from 'react';
import {
  View,
  Text,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { getStyles } from './loginScreen.styles';
import { CustomInput, PrimaryButton } from '@components';
import { useAppTheme } from '@theme';
import { useAppDispatch } from '../../../hooks/useAppDispatch';
import { loginWithPhone } from '../../../store/authSlice';
import { AuthStackParamList } from '../../../navigation/authStack';

type LoginNavProp = StackNavigationProp<AuthStackParamList, 'LoginScreen'>;

export const LoginScreen: React.FC = () => {
  const { colors } = useAppTheme();
  const styles = getStyles(colors);
  const navigation = useNavigation<LoginNavProp>();
  const dispatch = useAppDispatch();

  const [mobileNumber, setMobileNumber] = useState('');
  const [error, setError] = useState<string | undefined>(undefined);

  const handleLogin = () => {
    if (!mobileNumber) {
      setError('Mobile number is required');
      return;
    }
    if (mobileNumber.length < 10) {
      setError('Please enter a valid mobile number');
      return;
    }
    setError(undefined);
    dispatch(loginWithPhone(mobileNumber));
    navigation.navigate('OtpScreen', { mobileNumber });
  };

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <ScrollView
        contentContainerStyle={styles.scrollContainer}
        showsVerticalScrollIndicator={false}
      >
        <View style={styles.headerContainer}>
          <Text style={styles.title}>Welcome back</Text>
          <Text style={styles.subtitle}>Login to continue</Text>
        </View>

        <View style={styles.formContainer}>
          <CustomInput
            label="Mobile number"
            placeholder="+91 98765 43210"
            keyboardType="phone-pad"
            value={mobileNumber}
            onChangeText={(text) => {
              setMobileNumber(text);
              if (error) setError(undefined);
            }}
            error={error}
          />

          <PrimaryButton
            title="Login"
            onPress={handleLogin}
            style={{ marginTop: 12 }}
          />
        </View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
};
