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

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

export function Login({ onLogin }: LoginProps) {
  const usernameInputRef = useRef<HTMLInputElement>(null);
  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 [isSuccess, setIsSuccess] = useState(false);
  const [shakeCard, setShakeCard] = useState(false);

  useEffect(() => {
    usernameInputRef.current?.focus();
  }, []);

  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()) {
      setShakeCard(true);
      setTimeout(() => setShakeCard(false), 500);
      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) {
        setIsSuccess(true);
        onLogin(response.token);
      } else {
        setError(response.message || "Login failed");
        setShakeCard(true);
        setTimeout(() => setShakeCard(false), 500);
      }
    } catch (err) {
      console.error("Login error:", err);
      setError("An unexpected error occurred. Please try again.");
      setShakeCard(true);
      setTimeout(() => setShakeCard(false), 500);
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") {
      handleSubmit(e);
    }
  };

  return (
    <div
      className="card login-card"
      style={{
        maxWidth: "420px",
        margin: "6rem auto",
        padding: "2.5rem",
        background: "linear-gradient(135deg, var(--secondary-bg) 0%, var(--secondary-alt-bg) 100%)",
        position: "relative"
      }}
    >
      {isSubmitting && (
        <div
          style={{
            position: "absolute",
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: "rgba(0, 0, 0, 0.5)",
            borderRadius: "16px",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            zIndex: 10,
            backdropFilter: "blur(2px)"
          }}
        >
          <div
            style={{
              width: "48px",
              height: "48px",
              border: "4px solid rgba(255, 255, 255, 0.2)",
              borderTopColor: "white",
              borderRadius: "50%",
              animation: "spin 0.8s linear infinite"
            }}
          />
        </div>
      )}

      {isSuccess && (
        <div
          style={{
            position: "absolute",
            top: "50%",
            left: "50%",
            transform: "translate(-50%, -50%)",
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            gap: "1rem",
            animation: "fadeInScale 0.5s ease forwards",
            zIndex: 10
          }}
        >
          <div
            style={{
              width: "64px",
              height: "64px",
              borderRadius: "50%",
              backgroundColor: "#4caf50",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              fontSize: "2rem",
              color: "white",
              boxShadow: "0 0 20px rgba(76, 175, 80, 0.5)"
            }}
          >
            ✓
          </div>
          <span style={{ color: "#4caf50", fontWeight: 600, fontSize: "1.1rem" }}>
            Success!
          </span>
        </div>
      )}

      <h2
        style={{
          textAlign: "center",
          marginBottom: "0.5rem",
          fontSize: "2rem",
          fontWeight: 700
        }}
      >
        🎮 Login
      </h2>
      <p
        style={{
          textAlign: "center",
          color: "var(--text-muted)",
          marginBottom: "2rem",
          fontSize: "0.95rem"
        }}
      >
        Welcome back! Please sign in to continue.
      </p>

      <form onSubmit={handleSubmit} className="form-group">
        <div className="form-group" style={{ marginBottom: "1.5rem" }}>
          <label
            style={{
              display: "block",
              marginBottom: "0.5rem",
              fontWeight: 500,
              color: "var(--text-color)",
              fontSize: "0.95rem"
            }}
          >
            Username
          </label>
          <div
            style={{
              position: "relative",
              display: "flex",
              alignItems: "center"
            }}
          >
            <span
              style={{
                position: "absolute",
                left: "0.75rem",
                color: "var(--text-muted)",
                pointerEvents: "none",
                fontSize: "1.1rem"
              }}
            >
              👤
            </span>
            <input
              ref={usernameInputRef}
              type="text"
              value={username}
              onChange={(e) => {
                setUsername(e.target.value);
                if (fieldErrors.username) setFieldErrors({ ...fieldErrors, username: undefined });
              }}
              onKeyDown={handleKeyDown}
              placeholder="Enter your username"
              aria-label="Username"
              aria-invalid={!!fieldErrors.username}
              aria-describedby={fieldErrors.username ? "username-error" : undefined}
              style={{
                width: "100%",
                paddingLeft: "2.75rem",
                paddingRight: "0.75rem",
                paddingTop: "0.75rem",
                paddingBottom: "0.75rem",
                borderColor: fieldErrors.username ? "#f44336" : undefined,
                borderWidth: fieldErrors.username ? "2px" : "1px",
                fontSize: "1rem"
              }}
            />
          </div>
          {fieldErrors.username && (
            <span
              id="username-error"
              role="alert"
              style={{
                color: "#ff6b6b",
                fontSize: "0.85rem",
                marginTop: "0.5rem",
                display: "flex",
                alignItems: "center",
                gap: "0.25rem"
              }}
            >
              ⚠️ {fieldErrors.username}
            </span>
          )}
        </div>

        <div className="form-group" style={{ marginBottom: "2rem" }}>
          <label
            style={{
              display: "block",
              marginBottom: "0.5rem",
              fontWeight: 500,
              color: "var(--text-color)",
              fontSize: "0.95rem"
            }}
          >
            Password
          </label>
          <div
            style={{
              position: "relative",
              display: "flex",
              alignItems: "center"
            }}
          >
            <span
              style={{
                position: "absolute",
                left: "0.75rem",
                color: "var(--text-muted)",
                pointerEvents: "none",
                fontSize: "1.1rem"
              }}
            >
              🔒
            </span>
            <input
              type="password"
              value={password}
              onChange={(e) => {
                setPassword(e.target.value);
                if (fieldErrors.password) setFieldErrors({ ...fieldErrors, password: undefined });
              }}
              onKeyDown={handleKeyDown}
              placeholder="Enter your password"
              aria-label="Password"
              aria-invalid={!!fieldErrors.password}
              aria-describedby={fieldErrors.password ? "password-error" : undefined}
              style={{
                width: "100%",
                paddingLeft: "2.75rem",
                paddingRight: "0.75rem",
                paddingTop: "0.75rem",
                paddingBottom: "0.75rem",
                borderColor: fieldErrors.password ? "#f44336" : undefined,
                borderWidth: fieldErrors.password ? "2px" : "1px",
                fontSize: "1rem"
              }}
            />
          </div>
          {fieldErrors.password && (
            <span
              id="password-error"
              role="alert"
              style={{
                color: "#ff6b6b",
                fontSize: "0.85rem",
                marginTop: "0.5rem",
                display: "flex",
                alignItems: "center",
                gap: "0.25rem"
              }}
            >
              ⚠️ {fieldErrors.password}
            </span>
          )}
        </div>

        <button
          type="submit"
          style={{
            marginTop: "0.5rem",
            width: "100%",
            padding: "0.875rem",
            fontSize: "1rem",
            fontWeight: 600,
            opacity: isSubmitting ? 0.7 : 1,
            cursor: isSubmitting ? "not-allowed" : "pointer",
            background: "linear-gradient(135deg, var(--accent-color) 0%, var(--secondary-accent) 100%)",
            border: "none",
            transition: "transform 0.1s, box-shadow 0.2s"
          }}
          disabled={isSubmitting}
          onMouseEnter={(e) => {
            if (!isSubmitting) {
              e.currentTarget.style.transform = "translateY(-1px)";
              e.currentTarget.style.boxShadow = "0 4px 12px rgba(9, 109, 192, 0.4)";
            }
          }}
          onMouseLeave={(e) => {
            if (!isSubmitting) {
              e.currentTarget.style.transform = "translateY(0)";
              e.currentTarget.style.boxShadow = "none";
            }
          }}
          onMouseDown={(e) => {
            if (!isSubmitting) {
              e.currentTarget.style.transform = "translateY(0)";
            }
          }}
        >
          Login
        </button>
      </form>

      {error && (
        <div
          role="alert"
          style={{
            backgroundColor: "rgba(244, 67, 54, 0.15)",
            border: "1px solid rgba(244, 67, 54, 0.4)",
            color: "#ff6b6b",
            padding: "0.875rem 1rem",
            borderRadius: "8px",
            marginTop: "1.5rem",
            textAlign: "center",
            fontSize: "0.9rem",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            gap: "0.5rem"
          }}
        >
          ⚠️ {error}
        </div>
      )}

      <style>{`
        @keyframes spin {
          to { transform: rotate(360deg); }
        }

        @keyframes fadeInScale {
          from {
            opacity: 0;
            transform: translate(-50%, -40%) scale(0.8);
          }
          to {
            opacity: 1;
            transform: translate(-50%, -50%) scale(1);
          }
        }

        .login-card {
          animation: ${shakeCard ? "shake 0.5s ease" : "none"};
        }

        @keyframes shake {
          0%, 100% {
            transform: translateX(0);
          }
          20%, 60% {
            transform: translateX(-8px);
          }
          40%, 80% {
            transform: translateX(8px);
          }
        }
      `}</style>
    </div>
  );
}
