import React, { useCallback } from 'react';
import { View, Text, StyleSheet, KeyboardAvoidingView, Platform, ScrollView } from 'react-native';
import { colors } from '../../theme/colors';
import { spacing } from '../../theme/spacing';
import { typography } from '../../theme/typography';
import { Button, Input } from '../../components/ui';
import { useAuthStore } from '../../stores/auth.store';
import { useLogin } from './hooks';

export function LoginScreen(): React.JSX.Element {
  const styles = createStyles();
  const { login, isLoading, error, clearError } = useAuthStore();
  const { phone, password, phoneError, passwordError, setPhone, setPassword, validate } =
    useLogin();

  const handleLogin = useCallback(async () => {
    clearError();
    if (!validate()) return;

    const formattedPhone = `+7${phone}`;
    try {
      await login(formattedPhone, password);
    } catch {
      // Error is handled by the store
    }
  }, [phone, password, validate, login, clearError]);

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <ScrollView contentContainerStyle={styles.scrollContent} keyboardShouldPersistTaps="handled">
        <View style={styles.header}>
          <Text style={styles.logo}>MyFitCRM</Text>
          <Text style={styles.subtitle}>CRM-система для фитнес-клубов</Text>
        </View>

        <View style={styles.form}>
          <Input
            label="Телефон"
            placeholder="9001234567"
            prefix="+7"
            value={phone}
            onChangeText={setPhone}
            keyboardType="phone-pad"
            maxLength={10}
            error={phoneError ?? undefined}
            autoCapitalize="none"
          />

          <Input
            label="Пароль"
            placeholder="Введите пароль"
            value={password}
            onChangeText={setPassword}
            secureTextEntry
            error={passwordError ?? undefined}
            autoCapitalize="none"
          />

          {error && <Text style={styles.errorText}>{error}</Text>}

          <Button
            title="Войти"
            onPress={() => void handleLogin()}
            loading={isLoading}
            disabled={isLoading}
          />
        </View>
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

const createStyles = () =>
  StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: colors.background,
    },
    scrollContent: {
      flexGrow: 1,
      justifyContent: 'center',
      paddingHorizontal: spacing.xxl,
    },
    header: {
      alignItems: 'center',
      marginBottom: spacing.xxxl,
    },
    logo: {
      ...typography.h1,
      fontSize: 36,
      color: colors.primary,
      fontWeight: '700',
      marginBottom: spacing.sm,
    },
    subtitle: {
      ...typography.body,
      color: colors.textSecondary,
    },
    form: {
      width: '100%',
    },
    errorText: {
      ...typography.bodySmall,
      color: colors.error,
      textAlign: 'center',
      marginBottom: spacing.lg,
    },
  });
