import React, { useState } from 'react';
import { View, Text, TouchableOpacity, SafeAreaView, Alert } from 'react-native';
import { InputField, CheckBox, Button, InlineButton } from '@components';
import { styles } from './login.styles';
import authService from '../../services/authService';

interface LoginScreenProps {
  onLoginSuccess: (token: string) => void;
  onCreateAccount?: () => void;
  onForgotPassword?: () => void;
}

export function LoginScreen({
  onLoginSuccess,
  onCreateAccount,
  onForgotPassword,
}: LoginScreenProps) {
  const [emailOrPhone, setEmailOrPhone] = useState('');
  const [password, setPassword] = useState('');
  const [secureTextEntry, setSecureTextEntry] = useState(true);
  const [rememberMe, setRememberMe] = useState(false);
  const [loading, setLoading] = useState(false);

  const handleSignIn = async () => {
    if (!emailOrPhone.trim() || !password.trim()) {
      Alert.alert('Error', 'Please enter both email/phone number and password');
      return;
    }

    setLoading(true);

    try {
      const token = await authService.signIn(emailOrPhone, password);
      onLoginSuccess(token);
    } catch (error: any) {
      Alert.alert('Login Failed', error.message || 'Something went wrong');
    } finally {
      setLoading(false);
    }
  };

  const toggleSecureEntry = () => {
    setSecureTextEntry(prev => !prev);
  };

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.card}>
        {/* Header */}
        <View style={styles.headerContainer}>
          <Text style={styles.title}>Welcome Back</Text>
          <Text style={styles.subtitle}>
            Please enter your credentials to access your account.
          </Text>
        </View>

        {/* Email or Phone Input */}
        <InputField
          label="EMAIL OR PHONE NUMBER"
          placeholder="ujjwal@sentientgeeks.com"
          value={emailOrPhone}
          onChangeText={setEmailOrPhone}
          keyboardType="email-address"
          autoCapitalize="none"
          autoCorrect={false}
        />

        {/* Password Input */}
        <InputField
          label="PASSWORD"
          placeholder="••••••••"
          value={password}
          onChangeText={setPassword}
          secureTextEntry={secureTextEntry}
          autoCapitalize="none"
          autoCorrect={false}
          renderRightAccessory={() => (
            <TouchableOpacity
              style={styles.eyeButton}
              onPress={toggleSecureEntry}
              activeOpacity={0.7}
            >
              <Text style={styles.eyeText}>
                {secureTextEntry ? '👁️' : '🙈'}
              </Text>
            </TouchableOpacity>
          )}
        />

        {/* Remember Me & Forgot Password */}
        <View style={styles.rowContainer}>
          <CheckBox
            value={rememberMe}
            onValueChange={setRememberMe}
            label="Remember me"
          />
          <InlineButton
            onPress={onForgotPassword ?? (() => {})}
            highlightedText="Forgot password?"
            highlightedTextStyle={styles.forgotPasswordText}
          />
        </View>

        {/* Sign In Button */}
        <Button
          title="SIGN IN"
          onPress={handleSignIn}
          loading={loading}
        />

        {/* Divider */}
        <View style={styles.divider} />

        {/* Create Account */}
        <View style={styles.footerContainer}>
          <InlineButton
            onPress={onCreateAccount ?? (() => {})}
            text="Don't have an account?"
            highlightedText="Create one"
          />
        </View>
      </View>
    </SafeAreaView>
  );
}
