import { useState } from "react";
import { useNavigate, Link } from "react-router-dom";
import { FaUser, FaEnvelope, FaLock, FaSpinner, FaCheckCircle } from "react-icons/fa";
import { apiAccountRegisterCreate } from "@/api/generated/public/account";

export default function RegisterPage() {
  const navigate = useNavigate();
  
  const [formData, setFormData] = useState({
    username: "",
    email: "",
    password: "",
    password2: "",
  });
  
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);

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

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError("");

    // Validation
    if (!formData.username.trim() || !formData.email.trim() || !formData.password.trim()) {
      setError("Vyplňte prosím všechna pole");
      return;
    }

    if (formData.password !== formData.password2) {
      setError("Hesla se neshodují");
      return;
    }

    if (formData.password.length < 8) {
      setError("Heslo musí mít alespoň 8 znaků");
      return;
    }

    setIsLoading(true);
    try {
      await apiAccountRegisterCreate({
        username: formData.username,
        email: formData.email,
        password: formData.password,
        password2: formData.password2,
      });
      
      setSuccess(true);
      setTimeout(() => navigate("/login"), 2000);
    } catch (err: any) {
      const errorMessage = err.response?.data?.error || err.message || "Registrace se nezdařila";
      setError(errorMessage);
    } finally {
      setIsLoading(false);
    }
  }

  if (success) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-green-50 to-emerald-100 p-4">
        <div className="bg-white rounded-lg shadow-xl p-8 w-full max-w-md text-center">
          <FaCheckCircle className="text-green-500 text-6xl mx-auto mb-4" />
          <h1 className="text-2xl font-bold text-gray-800 mb-2">Registrace úspěšná!</h1>
          <p className="text-gray-600 mb-4">Váš účet byl vytvořen. Přesměrování na přihlášení...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-purple-50 to-pink-100 p-4">
      <div className="bg-white rounded-lg shadow-xl p-8 w-full max-w-md">
        <h1 className="text-3xl font-bold text-center mb-2 text-gray-800">Registrace</h1>
        <p className="text-center text-gray-600 mb-8">Vytvořte si účet na vontor.cz</p>
        
        {error && (
          <div className="mb-6 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg">
            <strong>Chyba:</strong> {error}
          </div>
        )}
        
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block mb-2 font-medium text-gray-700 flex items-center gap-2">
              <FaUser className="text-gray-500" />
              Uživatelské jméno
            </label>
            <input
              type="text"
              name="username"
              value={formData.username}
              onChange={handleChange}
              placeholder="username"
              className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"
              disabled={isLoading}
              required
            />
          </div>

          <div>
            <label className="block mb-2 font-medium text-gray-700 flex items-center gap-2">
              <FaEnvelope className="text-gray-500" />
              Email
            </label>
            <input
              type="email"
              name="email"
              value={formData.email}
              onChange={handleChange}
              placeholder="email@example.com"
              className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"
              disabled={isLoading}
              required
            />
          </div>
          
          <div>
            <label className="block mb-2 font-medium text-gray-700 flex items-center gap-2">
              <FaLock className="text-gray-500" />
              Heslo
            </label>
            <input
              type="password"
              name="password"
              value={formData.password}
              onChange={handleChange}
              placeholder="••••••••"
              className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"
              disabled={isLoading}
              required
              minLength={8}
            />
            <p className="text-xs text-gray-500 mt-1">Minimálně 8 znaků</p>
          </div>

          <div>
            <label className="block mb-2 font-medium text-gray-700 flex items-center gap-2">
              <FaLock className="text-gray-500" />
              Potvrďte heslo
            </label>
            <input
              type="password"
              name="password2"
              value={formData.password2}
              onChange={handleChange}
              placeholder="••••••••"
              className="w-full p-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"
              disabled={isLoading}
              required
            />
          </div>
          
          <button
            type="submit"
            disabled={isLoading}
            className="w-full bg-purple-600 text-white py-3 rounded-lg font-semibold hover:bg-purple-700 disabled:bg-gray-400 disabled:cursor-not-allowed transition flex items-center justify-center gap-2 mt-6"
          >
            {isLoading ? (
              <>
                <FaSpinner className="animate-spin" />
                Vytváření účtu...
              </>
            ) : (
              "Zaregistrovat se"
            )}
          </button>
        </form>

        <div className="mt-6 text-center text-gray-600">
          Již máte účet?{" "}
          <Link to="/login" className="text-purple-600 hover:text-purple-800 font-semibold hover:underline">
            Přihlaste se
          </Link>
        </div>
      </div>
    </div>
  );
}