"use client";

import { useState, useEffect, useRef } from "react";
import { BeadsLogo } from "@/components/BeadsLogo";

/**
 * Password login page for dashboard access control.
 *
 * Shown when heartbeads is started with --password flag.
 * Matches the design language of the 404 page and loading screen:
 * ECG flatline + animated heartbeat logo, clean centered form.
 *
 * This is NOT the ATProto/Bluesky sign-in (that's in the navbar).
 * This gate controls who can view the dashboard and API.
 */
export default function LoginPage() {
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [from, setFrom] = useState("/");
  const inputRef = useRef<HTMLInputElement>(null);

  // Read ?from= query param for post-login redirect (avoid useSearchParams / Suspense)
  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const fromParam = params.get("from");
    // Validate: only allow relative paths (prevent open redirect to external URLs)
    if (fromParam && fromParam.startsWith("/") && !fromParam.startsWith("//")) {
      setFrom(fromParam);
    }

    // Auto-focus the password input
    inputRef.current?.focus();
  }, []);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!password.trim()) return;

    setError("");
    setLoading(true);

    try {
      const res = await fetch("/api/auth", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ password: password.trim() }),
      });

      if (res.ok) {
        window.location.href = from;
      } else {
        const data = await res.json();
        setError(data.error || "Invalid password");
      }
    } catch {
      setError("Connection error");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="h-screen flex flex-col items-center justify-center bg-white dark:bg-zinc-900 text-zinc-800 dark:text-zinc-200 px-6 select-none">
      {/* ECG flatline + animated heartbeat logo */}
      <div className="relative w-full max-w-xs mb-6">
        <svg
          viewBox="0 0 320 40"
          fill="none"
          className="w-full text-zinc-200 dark:text-zinc-700"
          aria-hidden="true"
        >
          <line
            x1="0"
            y1="20"
            x2="320"
            y2="20"
            stroke="currentColor"
            strokeWidth="1.5"
            strokeLinecap="round"
            strokeDasharray="4 6"
            opacity="0.6"
          />
        </svg>
        <div className="absolute inset-0 flex items-center justify-center">
          <div className="bg-white dark:bg-zinc-900 px-4">
            <BeadsLogo className="w-10 h-10 text-emerald-500" />
          </div>
        </div>
      </div>

      {/* Title */}
      <h1
        className="text-lg font-semibold text-zinc-900 dark:text-zinc-100 mb-1 animate-fade-in"
      >
        heartbeads
      </h1>
      <p
        className="text-sm text-zinc-400 dark:text-zinc-500 mb-6 animate-fade-in"
        style={{ animationDelay: "0.05s" }}
      >
        This dashboard is password-protected.
      </p>

      {/* Login form */}
      <form
        onSubmit={handleSubmit}
        className="w-full max-w-xs animate-fade-in"
        style={{ animationDelay: "0.1s" }}
      >
        <input
          ref={inputRef}
          type="password"
          value={password}
          onChange={(e) => {
            setPassword(e.target.value);
            if (error) setError("");
          }}
          placeholder="Enter password"
          className="w-full rounded-lg border border-zinc-200 dark:border-zinc-700 bg-zinc-50 dark:bg-zinc-800 px-4 py-2.5 text-sm text-zinc-900 dark:text-zinc-100 placeholder:text-zinc-400 dark:placeholder:text-zinc-500 focus:outline-none focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 transition-colors"
          autoComplete="current-password"
          disabled={loading}
        />

        {/* Error message */}
        {error && (
          <p className="mt-2 text-xs text-red-500 animate-fade-in">
            {error}
          </p>
        )}

        <button
          type="submit"
          disabled={loading || !password.trim()}
          className="mt-3 w-full inline-flex items-center justify-center gap-2 px-5 py-2.5 rounded-full bg-emerald-500 text-white text-sm font-medium shadow-sm hover:bg-emerald-600 hover:shadow-md transition-all duration-200 ease-out disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-emerald-500 disabled:hover:shadow-sm"
        >
          {loading ? (
            <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
          ) : (
            <svg
              className="w-4 h-4"
              fill="none"
              viewBox="0 0 24 24"
              strokeWidth={1.5}
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M13.5 10.5V6.75a4.5 4.5 0 119 0v3.75M3.75 21.75h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H3.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z"
              />
            </svg>
          )}
          {loading ? "Unlocking..." : "Unlock"}
        </button>
      </form>

      {/* Footer */}
      <p
        className="mt-10 text-[11px] text-zinc-300 dark:text-zinc-600 animate-fade-in"
        style={{ animationDelay: "0.15s" }}
      >
        password protection enabled
      </p>
    </div>
  );
}
