import React, { useState } from 'react';
import {
  Text,
  View,
  TextInput,
  TouchableOpacity,
  KeyboardAvoidingView,
  Platform,
  ScrollView,
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/Ionicons';
import { getStyles } from './login.styles';
import { useTheme } from '../../theme';

export const LoginScreen = () => {
  const navigation = useNavigation<any>();
  const { theme: colors } = useTheme();
  const styles = getStyles(colors);
  const [tenancy, setTenancy] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const handleLogin = async () => {
    setError('');
    if (!tenancy.trim()) {
      setError('Tenancy name is required');
      return;
    }
    if (!email.trim()) {
      setError('Email address is required');
      return;
    }
    if (!password.trim()) {
      setError('Password is required');
      return;
    }

    setLoading(true);
    try {
      const mockToken = 'dummy-jwt-token-for-crm';
      await AsyncStorage.setItem('userToken', mockToken);
      await AsyncStorage.setItem('tenancyName', tenancy);
      setLoading(false);

      navigation.reset({
        index: 0,
        routes: [{ name: 'DrawerStack' }], // root-level stack name stays as-is
      });
    } catch {
      setLoading(false);
      setError('Failed to sign in. Please try again.');
    }
  };

  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      style={styles.container}
    >
      <ScrollView
        contentContainerStyle={styles.scrollContainer}
        keyboardShouldPersistTaps="handled"
      >
        <View style={styles.headerContainer}>
          <View style={styles.logoCircle}>
            <Icon name="cube" size={40} color={colors.icon} />
          </View>
          <Text style={styles.title}>Convex CRM</Text>
          <Text style={styles.subtitle}>
            Enter details to access your workspace
          </Text>
        </View>

        <View style={styles.formCard}>
          {error ? (
            <View style={styles.errorBanner}>
              <Icon name="alert-circle" size={20} color="#EF4444" />
              <Text style={styles.errorText}>{error}</Text>
            </View>
          ) : null}

          {/* Tenancy Field */}
          <View style={styles.inputContainer}>
            <Text style={styles.label}>Tenancy Name</Text>
            <View style={styles.inputWrapper}>
              <Icon
                name="business-outline"
                size={20}
                color={colors.textSecondary}
                style={styles.inputIcon}
              />
              <TextInput
                style={styles.input}
                placeholder="company-name"
                placeholderTextColor={colors.textMuted}
                value={tenancy}
                onChangeText={setTenancy}
                autoCapitalize="none"
                autoCorrect={false}
              />
            </View>
          </View>

          {/* Email Field */}
          <View style={styles.inputContainer}>
            <Text style={styles.label}>Email Address</Text>
            <View style={styles.inputWrapper}>
              <Icon
                name="mail-outline"
                size={20}
                color={colors.textSecondary}
                style={styles.inputIcon}
              />
              <TextInput
                style={styles.input}
                placeholder="name@company.com"
                placeholderTextColor={colors.textMuted}
                value={email}
                onChangeText={setEmail}
                keyboardType="email-address"
                autoCapitalize="none"
                autoCorrect={false}
              />
            </View>
          </View>

          {/* Password Field */}
          <View style={styles.inputContainer}>
            <Text style={styles.label}>Password</Text>
            <View style={styles.inputWrapper}>
              <Icon
                name="lock-closed-outline"
                size={20}
                color={colors.textSecondary}
                style={styles.inputIcon}
              />
              <TextInput
                style={styles.input}
                placeholder="••••••••"
                placeholderTextColor={colors.textMuted}
                value={password}
                onChangeText={setPassword}
                secureTextEntry
                autoCapitalize="none"
                autoCorrect={false}
              />
            </View>
          </View>

          {/* Sign In Button */}
          <TouchableOpacity
            style={styles.button}
            activeOpacity={0.8}
            onPress={handleLogin}
            disabled={loading}
          >
            <Text style={styles.buttonText}>
              {loading ? 'Signing In...' : 'Sign In'}
            </Text>
          </TouchableOpacity>
        </View>

        <View style={styles.footer}>
          <Text style={styles.footerText}>Secure SSL encrypted workspace</Text>
        </View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
};
