import { useState } from "react";
import { LoginRequest, LoginResponse } from "../items";

interface LoginProps {
  onLogin: (token: string) => void;
}

export function Login({ onLogin }: LoginProps) {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<{ username?: string, password?: string }>({});

  const validateForm = () => {
    const errors: { username?: string, password?: string } = {};
    if (!username.trim()) errors.username = "Username is required";
    if (!password) errors.password = "Password is required";
    setFieldErrors(errors);
    return Object.keys(errors).length === 0;
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");

    if (!validateForm()) return;

    setIsSubmitting(true);

    try {
      const req = LoginRequest.create({ username: username.trim(), password });
      const body = LoginRequest.encode(req).finish();

      const res = await fetch("/auth/login", {
        method: "POST",
        body,
        headers: {
          "Content-Type": "application/octet-stream",
        },
      });

      const buffer = await res.arrayBuffer();
      const response = LoginResponse.decode(new Uint8Array(buffer));

      if (response.success) {
        onLogin(response.token);
      } else {
        setError(response.message || "Login failed");
      }
    } catch (err) {
      console.error("Login error:", err);
      setError("An unexpected error occurred. Please try again.");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="card" style={{ maxWidth: "400px", margin: "4rem auto" }}>
      <h2 style={{ textAlign: "center", marginBottom: "2rem" }}>🎮 Login</h2>
      <form onSubmit={handleSubmit} className="form-group">
        <div className="form-group">
          <label>Username</label>
          <input
            type="text"
            value={username}
            onChange={(e) => {
              setUsername(e.target.value);
              if (fieldErrors.username) setFieldErrors({ ...fieldErrors, username: undefined });
            }}
            placeholder="Enter your username"
            style={{
              borderColor: fieldErrors.username ? "#f44336" : undefined,
              borderWidth: fieldErrors.username ? "2px" : undefined
            }}
          />
          {fieldErrors.username && (
            <span style={{ color: "#f44336", fontSize: "0.85rem", marginTop: "0.25rem", display: "block" }}>
              {fieldErrors.username}
            </span>
          )}
        </div>
        <div className="form-group">
          <label>Password</label>
          <input
            type="password"
            value={password}
            onChange={(e) => {
              setPassword(e.target.value);
              if (fieldErrors.password) setFieldErrors({ ...fieldErrors, password: undefined });
            }}
            placeholder="Enter your password"
            style={{
              borderColor: fieldErrors.password ? "#f44336" : undefined,
              borderWidth: fieldErrors.password ? "2px" : undefined
            }}
          />
          {fieldErrors.password && (
            <span style={{ color: "#f44336", fontSize: "0.85rem", marginTop: "0.25rem", display: "block" }}>
              {fieldErrors.password}
            </span>
          )}
        </div>
        <button
          type="submit"
          style={{ marginTop: "1rem", width: "100%", opacity: isSubmitting ? 0.7 : 1, cursor: isSubmitting ? "not-allowed" : "pointer" }}
          disabled={isSubmitting}
        >
          {isSubmitting ? (
            <>
              <span
                style={{
                  width: "14px",
                  height: "14px",
                  border: "2px solid rgba(255,255,255,0.3)",
                  borderTopColor: "white",
                  borderRadius: "50%",
                  animation: "spin 0.8s linear infinite",
                  display: "inline-block",
                  marginRight: "0.5rem"
                }}
              ></span>
              Logging in...
            </>
          ) : (
            "Login"
          )}
        </button>
      </form>
      {error && (
        <div
          style={{
            backgroundColor: "rgba(244, 67, 54, 0.1)",
            border: "1px solid rgba(244, 67, 54, 0.3)",
            color: "#ff6b6b",
            padding: "1rem",
            borderRadius: "8px",
            marginTop: "1rem",
            textAlign: "center",
            fontSize: "0.9rem"
          }}
        >
          ⚠️ {error}
        </div>
      )}
      <style>{`
        @keyframes spin {
          to { transform: rotate(360deg); }
        }
      `}</style>
    </div>
  );
}
