import { useState, useCallback } from 'react';

interface UseLoginReturn {
  phone: string;
  password: string;
  phoneError: string | null;
  passwordError: string | null;
  setPhone: (value: string) => void;
  setPassword: (value: string) => void;
  validate: () => boolean;
  reset: () => void;
}

export function useLogin(): UseLoginReturn {
  const [phone, setPhone] = useState('');
  const [password, setPassword] = useState('');
  const [phoneError, setPhoneError] = useState<string | null>(null);
  const [passwordError, setPasswordError] = useState<string | null>(null);

  const handleSetPhone = useCallback((value: string) => {
    const cleaned = value.replace(/[^0-9]/g, '');
    setPhone(cleaned);
    if (phoneError) setPhoneError(null);
  }, [phoneError]);

  const handleSetPassword = useCallback((value: string) => {
    setPassword(value);
    if (passwordError) setPasswordError(null);
  }, [passwordError]);

  const validate = useCallback((): boolean => {
    let isValid = true;

    if (!phone || phone.length < 10) {
      setPhoneError('Введите корректный номер телефона');
      isValid = false;
    } else {
      setPhoneError(null);
    }

    if (!password || password.length < 4) {
      setPasswordError('Пароль должен содержать минимум 4 символа');
      isValid = false;
    } else {
      setPasswordError(null);
    }

    return isValid;
  }, [phone, password]);

  const reset = useCallback(() => {
    setPhone('');
    setPassword('');
    setPhoneError(null);
    setPasswordError(null);
  }, []);

  return {
    phone,
    password,
    phoneError,
    passwordError,
    setPhone: handleSetPhone,
    setPassword: handleSetPassword,
    validate,
    reset,
  };
}
