import React, { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { signUp } from '../../services/pocketbaseService';
import { useAuth } from '../../contexts/AuthContext';
import { FaEye, FaEyeSlash, FaUser, FaEnvelope, FaLock } from 'react-icons/fa';
import MobileLogo from '../components/MobileLogo';
import { FiHome } from 'react-icons/fi';

const MobileRegister = () => {
  const navigate = useNavigate();
  const { setUser } = useAuth();
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    confirmPassword: ''
  });
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError('');

    if (formData.password !== formData.confirmPassword) {
      setError('Пароли не совпадают');
      return;
    }

    if (formData.username.length < 3 || formData.username.length > 20) {
      setError('Имя пользователя должно быть от 3 до 20 символов');
      return;
    }

    if (!/^[a-zA-Z0-9_-]+$/.test(formData.username)) {
      setError('Имя пользователя может содержать только буквы, цифры, дефис и подчеркивание');
      return;
    }

    if (formData.password.length < 6) {
      setError('Пароль должен быть не менее 6 символов');
      return;
    }

    setLoading(true);

    try {
      const { user } = await signUp(formData.username, formData.password, formData.email);
      setUser(user);
      navigate('/');
    } catch (err) {
      if (err.message.includes('username')) {
        setError('Это имя пользователя уже занято');
      } else if (err.message.includes('email')) {
        setError('Этот email уже зарегистрирован');
      } else {
        setError(err.message || 'Не удалось зарегистрироваться');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-campfire-dark flex flex-col justify-center items-center p-4">
      <div className="w-full flex flex-col items-center mb-6">
        <MobileLogo className="w-20 h-20 mb-2" />
        <Link to="/" className="flex items-center gap-2 text-campfire-amber hover:text-campfire-ember text-sm font-medium mt-2">
          <FiHome /> На главную
        </Link>
      </div>
      <div className="w-full max-w-md">
        <div className="bg-campfire-charcoal/20 backdrop-blur-md border border-campfire-ash/30 rounded-xl p-6">
          <h1 className="text-2xl font-bold text-campfire-light mb-6 text-center">Регистрация</h1>
          
          {error && (
            <div className="bg-status-error/20 text-status-error p-3 rounded-lg mb-4 text-center">
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <FaUser className="text-campfire-ash" />
              </div>
              <input
                type="text"
                name="username"
                value={formData.username}
                onChange={handleChange}
                placeholder="Имя пользователя"
                required
                pattern="[a-zA-Z0-9_-]+"
                title="Только буквы, цифры, дефис и подчеркивание"
                className="w-full pl-10 pr-4 py-2 bg-campfire-charcoal/20 border border-campfire-ash/30 rounded-lg text-campfire-light placeholder-campfire-ash focus:outline-none focus:border-campfire-amber"
              />
            </div>

            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <FaEnvelope className="text-campfire-ash" />
              </div>
              <input
                type="email"
                name="email"
                value={formData.email}
                onChange={handleChange}
                placeholder="Email"
                required
                className="w-full pl-10 pr-4 py-2 bg-campfire-charcoal/20 border border-campfire-ash/30 rounded-lg text-campfire-light placeholder-campfire-ash focus:outline-none focus:border-campfire-amber"
              />
            </div>

            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <FaLock className="text-campfire-ash" />
              </div>
              <input
                type={showPassword ? 'text' : 'password'}
                name="password"
                value={formData.password}
                onChange={handleChange}
                placeholder="Пароль"
                required
                minLength="6"
                className="w-full pl-10 pr-12 py-2 bg-campfire-charcoal/20 border border-campfire-ash/30 rounded-lg text-campfire-light placeholder-campfire-ash focus:outline-none focus:border-campfire-amber"
              />
              <button
                type="button"
                onClick={() => setShowPassword(!showPassword)}
                className="absolute inset-y-0 right-0 pr-3 flex items-center"
              >
                {showPassword ? (
                  <FaEyeSlash className="text-campfire-ash hover:text-campfire-light" />
                ) : (
                  <FaEye className="text-campfire-ash hover:text-campfire-light" />
                )}
              </button>
            </div>

            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <FaLock className="text-campfire-ash" />
              </div>
              <input
                type={showConfirmPassword ? 'text' : 'password'}
                name="confirmPassword"
                value={formData.confirmPassword}
                onChange={handleChange}
                placeholder="Подтвердите пароль"
                required
                minLength="6"
                className="w-full pl-10 pr-12 py-2 bg-campfire-charcoal/20 border border-campfire-ash/30 rounded-lg text-campfire-light placeholder-campfire-ash focus:outline-none focus:border-campfire-amber"
              />
              <button
                type="button"
                onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                className="absolute inset-y-0 right-0 pr-3 flex items-center"
              >
                {showConfirmPassword ? (
                  <FaEyeSlash className="text-campfire-ash hover:text-campfire-light" />
                ) : (
                  <FaEye className="text-campfire-ash hover:text-campfire-light" />
                )}
              </button>
            </div>

            <button
              type="submit"
              disabled={loading}
              className="w-full py-2 bg-campfire-amber text-campfire-dark font-semibold rounded-lg hover:bg-campfire-amber/90 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {loading ? (
                <div className="flex items-center justify-center">
                  <div className="animate-spin rounded-full h-5 w-5 border-t-2 border-b-2 border-campfire-dark"></div>
                </div>
              ) : (
                'Зарегистрироваться'
              )}
            </button>
          </form>

          <div className="mt-4 text-center">
            <p className="text-campfire-ash">
              Уже есть аккаунт?{' '}
              <Link to="/auth/login" className="text-campfire-amber hover:text-campfire-amber/90">
                Войти
              </Link>
            </p>
          </div>
        </div>
      </div>
    </div>
  );
};

export default MobileRegister; 