// assets/js/pages/auth/RegisterApp.js
const { useState, useEffect } = React;

const RegisterApp = () => {
  const [formData, setFormData] = useState({
    name: "",
    email: "",
    nrp: "",
    phone: "",
    password: "",
    confirmPassword: "",
  });
  const [loading, setLoading] = useState(false);
  const [toast, setToast] = useState(null);
  const [errors, setErrors] = useState({});
  const [passwordStrength, setPasswordStrength] = useState("");

  const state = { setErrors, setLoading, setToast };
  const handlers = useRegisterHandlers(state);

  useEffect(() => {
    const user = AuthUtils.getCurrentUser();
    if (AuthUtils.isAuthenticated() && user?.role) {
      AuthUtils.redirectBasedOnRole(user);
    }
  }, []);

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

    if (name === "password") {
      setPasswordStrength(Helpers.checkPasswordStrength(value));
    }

    if (errors[name]) {
      setErrors((prev) => ({ ...prev, [name]: "" }));
    }
  };

  const getPasswordStrengthColor = () => {
    if (passwordStrength === "weak") return "text-red-400";
    if (passwordStrength === "medium") return "text-yellow-400";
    if (passwordStrength === "strong") return "text-green-400";
    return "";
  };

  const getPasswordStrengthText = () => {
    if (passwordStrength === "weak") return "⚠️ Password lemah";
    if (passwordStrength === "medium") return "✓ Password sedang";
    if (passwordStrength === "strong") return "✓ Password kuat";
    return "";
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-900 via-blue-900 to-slate-900 p-5">
      <div className="bg-gradient-to-br from-slate-800 to-slate-900 rounded-3xl shadow-2xl overflow-hidden max-w-lg w-full my-8 border border-slate-700">
        {/* Header */}
        <div className="bg-gradient-to-r from-blue-600 via-blue-700 to-indigo-700 text-white p-10 text-center relative overflow-hidden">
          <div className="absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PHBhdHRlcm4gaWQ9ImdyaWQiIHdpZHRoPSI2MCIgaGVpZ2h0PSI2MCIgcGF0dGVyblVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+PHBhdGggZD0iTSAxMCAwIEwgMCAwIDAgMTAiIGZpbGw9Im5vbmUiIHN0cm9rZT0id2hpdGUiIHN0cm9rZS1vcGFjaXR5PSIwLjEiIHN0cm9rZS13aWR0aD0iMSIvPjwvcGF0dGVybj48L2RlZnM+PHJlY3Qgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgZmlsbD0idXJsKCNncmlkKSIvPjwvc3ZnPg==')] opacity-20"></div>
          <h1 className="text-4xl font-bold mb-2 relative z-10">🔍 Register</h1>
          <p className="text-blue-100 relative z-10">
            Buat akun Lost & Found System
          </p>
        </div>

        {/* Body */}
        <div className="p-10">
          <form
            onSubmit={(e) => handlers.handleSubmit(e, formData)}
            className="space-y-5"
          >
            {/* Name */}
            <div>
              <label className="block text-slate-300 font-semibold mb-2">
                Nama Lengkap
              </label>
              <input
                type="text"
                name="name"
                value={formData.name}
                onChange={handleChange}
                placeholder="John Doe"
                className={`w-full px-4 py-3 bg-slate-700 border-2 rounded-xl text-white placeholder-slate-400 focus:outline-none transition ${
                  errors.name
                    ? "border-red-500 focus:border-red-500"
                    : "border-slate-600 focus:border-blue-500"
                }`}
                required
              />
              {errors.name && (
                <p className="text-red-400 text-sm mt-1">{errors.name}</p>
              )}
            </div>

            {/* Email */}
            <div>
              <label className="block text-slate-300 font-semibold mb-2">
                Email
              </label>
              <input
                type="email"
                name="email"
                value={formData.email}
                onChange={handleChange}
                placeholder="mahasiswa@example.com"
                className={`w-full px-4 py-3 bg-slate-700 border-2 rounded-xl text-white placeholder-slate-400 focus:outline-none transition ${
                  errors.email
                    ? "border-red-500 focus:border-red-500"
                    : "border-slate-600 focus:border-blue-500"
                }`}
                required
              />
              {errors.email && (
                <p className="text-red-400 text-sm mt-1">{errors.email}</p>
              )}
            </div>

            {/* NRP & Phone */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="block text-slate-300 font-semibold mb-2">
                  NRP
                </label>
                <input
                  type="text"
                  name="nrp"
                  value={formData.nrp}
                  onChange={handleChange}
                  placeholder="5026211234"
                  className={`w-full px-4 py-3 bg-slate-700 border-2 rounded-xl text-white placeholder-slate-400 focus:outline-none transition ${
                    errors.nrp
                      ? "border-red-500 focus:border-red-500"
                      : "border-slate-600 focus:border-blue-500"
                  }`}
                  required
                />
                {errors.nrp && (
                  <p className="text-red-400 text-sm mt-1">{errors.nrp}</p>
                )}
              </div>

              <div>
                <label className="block text-slate-300 font-semibold mb-2">
                  No. Telepon
                </label>
                <input
                  type="tel"
                  name="phone"
                  value={formData.phone}
                  onChange={handleChange}
                  placeholder="08123456789"
                  className={`w-full px-4 py-3 bg-slate-700 border-2 rounded-xl text-white placeholder-slate-400 focus:outline-none transition ${
                    errors.phone
                      ? "border-red-500 focus:border-red-500"
                      : "border-slate-600 focus:border-blue-500"
                  }`}
                  required
                />
                {errors.phone && (
                  <p className="text-red-400 text-sm mt-1">{errors.phone}</p>
                )}
              </div>
            </div>

            {/* Password */}
            <div>
              <label className="block text-slate-300 font-semibold mb-2">
                Password
              </label>
              <input
                type="password"
                name="password"
                value={formData.password}
                onChange={handleChange}
                placeholder="********"
                className={`w-full px-4 py-3 bg-slate-700 border-2 rounded-xl text-white placeholder-slate-400 focus:outline-none transition ${
                  errors.password
                    ? "border-red-500 focus:border-red-500"
                    : "border-slate-600 focus:border-blue-500"
                }`}
                required
              />
              {passwordStrength && (
                <p className={`text-sm mt-1 ${getPasswordStrengthColor()}`}>
                  {getPasswordStrengthText()}
                </p>
              )}
              {errors.password && (
                <p className="text-red-400 text-sm mt-1">{errors.password}</p>
              )}
            </div>

            {/* Confirm Password */}
            <div>
              <label className="block text-slate-300 font-semibold mb-2">
                Konfirmasi Password
              </label>
              <input
                type="password"
                name="confirmPassword"
                value={formData.confirmPassword}
                onChange={handleChange}
                placeholder="********"
                className={`w-full px-4 py-3 bg-slate-700 border-2 rounded-xl text-white placeholder-slate-400 focus:outline-none transition ${
                  errors.confirmPassword
                    ? "border-red-500 focus:border-red-500"
                    : "border-slate-600 focus:border-blue-500"
                }`}
                required
              />
              {errors.confirmPassword && (
                <p className="text-red-400 text-sm mt-1">
                  {errors.confirmPassword}
                </p>
              )}
            </div>

            {/* Submit Button */}
            <button
              type="submit"
              disabled={loading}
              className="w-full py-4 bg-gradient-to-r from-blue-600 to-blue-700 text-white font-bold rounded-xl hover:from-blue-700 hover:to-blue-800 transition transform hover:-translate-y-0.5 hover:shadow-lg hover:shadow-blue-500/50 disabled:from-slate-600 disabled:to-slate-700 disabled:cursor-not-allowed disabled:transform-none mt-2"
            >
              {loading ? (
                <span className="flex items-center justify-center">
                  <svg
                    className="animate-spin h-5 w-5 mr-3"
                    viewBox="0 0 24 24"
                  >
                    <circle
                      className="opacity-25"
                      cx="12"
                      cy="12"
                      r="10"
                      stroke="currentColor"
                      strokeWidth="4"
                      fill="none"
                    />
                    <path
                      className="opacity-75"
                      fill="currentColor"
                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
                    />
                  </svg>
                  Registering...
                </span>
              ) : (
                "Register"
              )}
            </button>
          </form>

          {/* Divider */}
          <div className="relative my-8">
            <div className="absolute inset-0 flex items-center">
              <div className="w-full border-t border-slate-700"></div>
            </div>
            <div className="relative flex justify-center text-sm">
              <span className="px-4 bg-slate-800 text-slate-400">atau</span>
            </div>
          </div>

          {/* Login Link */}
          <div className="text-center">
            <p className="text-slate-300">
              Sudah punya akun?{" "}
              <a
                href="/login"
                className="text-blue-400 font-semibold hover:text-blue-300 hover:underline"
              >
                Login disini
              </a>
            </p>
          </div>

          {/* Back to Home */}
          <div className="text-center mt-4">
            <a
              href="/"
              className="text-slate-400 text-sm hover:text-blue-400 transition"
            >
              ← Kembali ke Beranda
            </a>
          </div>
        </div>
      </div>

      {/* Toast */}
      {toast && (
        <Toast
          message={toast.message}
          type={toast.type}
          onClose={() => setToast(null)}
        />
      )}
    </div>
  );
};

ReactDOM.render(<RegisterApp />, document.getElementById("root"));
