import React, { useState, useEffect } from "react";
import { useApp } from "../store";
import { login, register, getRegistrationStatus } from "../api";
import { Flame, LogIn, UserPlus, Eye, EyeOff, AlertCircle } from "lucide-react";

export default function LoginPage() {
  const { dispatch } = useApp();
  const [isLogin, setIsLogin] = useState(true);
  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [registrationEnabled, setRegistrationEnabled] = useState(true);
  const [checkingRegistration, setCheckingRegistration] = useState(true);

  useEffect(() => {
    (async () => {
      try {
        const data = await getRegistrationStatus();
        setRegistrationEnabled(data.registration_enabled);
      } catch {
        setRegistrationEnabled(true);
      } finally {
        setCheckingRegistration(false);
      }
    })();
  }, []);

  async function handleSubmit(e) {
    e.preventDefault();
    setError("");
    setLoading(true);
    try {
      let data;
      if (isLogin) {
        data = await login(username, password);
      } else {
        data = await register(username, email, password);
      }
      dispatch({ type: "SET_AUTH", token: data.token, user: data.user });
    } catch (err) {
      setError(err.message || "Something went wrong");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="min-h-screen bg-anton-bg flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <div className="w-16 h-16 mx-auto mb-4 rounded-2xl bg-gradient-to-br from-anton-accent to-red-600 flex items-center justify-center shadow-lg shadow-anton-accent/20">
            <Flame size={32} className="text-white" />
          </div>
          <h1 className="text-3xl font-bold text-white">Son of Anton</h1>
          <p className="text-anton-muted mt-1 text-sm">Avatar of All Elements of Code</p>
        </div>

        <div className="bg-anton-card border border-anton-border rounded-2xl p-6 shadow-xl">
          {!checkingRegistration && registrationEnabled && (
            <div className="flex mb-6 bg-anton-bg rounded-xl p-1">
              <button onClick={() => { setIsLogin(true); setError(""); }}
                className={`flex-1 py-2 px-4 rounded-lg text-sm font-medium transition ${isLogin ? "bg-anton-accent text-white" : "text-anton-muted hover:text-white"}`}>
                Sign In
              </button>
              <button onClick={() => { setIsLogin(false); setError(""); }}
                className={`flex-1 py-2 px-4 rounded-lg text-sm font-medium transition ${!isLogin ? "bg-anton-accent text-white" : "text-anton-muted hover:text-white"}`}>
                Register
              </button>
            </div>
          )}

          {error && (
            <div className="mb-4 p-3 bg-red-500/10 border border-red-500/30 rounded-lg flex items-center gap-2 text-red-400 text-sm">
              <AlertCircle size={16} className="shrink-0" />
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="text-xs text-anton-muted mb-1 block">Username</label>
              <input type="text" value={username} onChange={(e) => setUsername(e.target.value)}
                placeholder="Enter username" required autoFocus
                className="w-full bg-anton-bg border border-anton-border rounded-xl px-4 py-3 text-white text-sm focus:outline-none focus:border-anton-accent transition" />
            </div>

            {!isLogin && (
              <div>
                <label className="text-xs text-anton-muted mb-1 block">Email</label>
                <input type="email" value={email} onChange={(e) => setEmail(e.target.value)}
                  placeholder="Enter email" required
                  className="w-full bg-anton-bg border border-anton-border rounded-xl px-4 py-3 text-white text-sm focus:outline-none focus:border-anton-accent transition" />
              </div>
            )}

            <div>
              <label className="text-xs text-anton-muted mb-1 block">Password</label>
              <div className="relative">
                <input type={showPassword ? "text" : "password"} value={password} onChange={(e) => setPassword(e.target.value)}
                  placeholder="Enter password" required
                  className="w-full bg-anton-bg border border-anton-border rounded-xl px-4 py-3 pr-10 text-white text-sm focus:outline-none focus:border-anton-accent transition" />
                <button type="button" onClick={() => setShowPassword(!showPassword)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-anton-muted hover:text-white transition">
                  {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
                </button>
              </div>
            </div>

            <button type="submit" disabled={loading}
              className="w-full bg-anton-accent text-white rounded-xl py-3 font-medium hover:opacity-90 transition disabled:opacity-50 flex items-center justify-center gap-2">
              {loading ? (
                <span className="w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
              ) : isLogin ? (
                <><LogIn size={18} /> Sign In</>
              ) : (
                <><UserPlus size={18} /> Create Account</>
              )}
            </button>
          </form>

          {!checkingRegistration && !registrationEnabled && (
            <div className="mt-4 p-3 bg-yellow-500/10 border border-yellow-500/30 rounded-lg text-yellow-400 text-xs text-center">
              Registration is currently disabled. Contact your administrator.
            </div>
          )}
        </div>

        <p className="text-center text-anton-muted text-xs mt-6">
          Created by Mahmoud Aglan — AL-Arcade
        </p>
      </div>
    </div>
  );
}