"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/lib/auth";
import { startDeviceFlow, pollDeviceToken } from "@/lib/auth";
import { KeyRound, Globe, Loader2, CheckCircle, Copy, ExternalLink } from "lucide-react";

type AuthMode = "token" | "device";

export default function LoginPage() {
  const router = useRouter();
  const { login } = useAuth();

  const [mode, setMode] = useState<AuthMode>("token");
  const [serverUrl, setServerUrl] = useState("https://git.clawmem.ai/api/v3");
  const [token, setToken] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  // Device flow state
  const [deviceCode, setDeviceCode] = useState("");
  const [userCode, setUserCode] = useState("");
  const [verificationUri, setVerificationUri] = useState("");
  const [polling, setPolling] = useState(false);
  const [copied, setCopied] = useState(false);

  async function handleTokenLogin(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setLoading(true);

    const ok = await login(serverUrl, token);
    setLoading(false);

    if (ok) {
      router.push("/");
    } else {
      setError("Invalid server URL or token. Please check and try again.");
    }
  }

  async function handleStartDeviceFlow() {
    setError("");
    setLoading(true);

    const flow = await startDeviceFlow(serverUrl);
    setLoading(false);

    if (!flow) {
      setError("Device flow not available on this server.");
      return;
    }

    setDeviceCode(flow.deviceCode);
    setUserCode(flow.userCode);
    setVerificationUri(flow.verificationUri);

    // Start polling
    setPolling(true);
    const interval = setInterval(async () => {
      const accessToken = await pollDeviceToken(serverUrl, flow.deviceCode);
      if (accessToken) {
        clearInterval(interval);
        setPolling(false);
        const ok = await login(serverUrl, accessToken);
        if (ok) router.push("/");
      }
    }, (flow.interval || 5) * 1000);

    // Auto-stop after expiry
    setTimeout(() => {
      clearInterval(interval);
      setPolling(false);
    }, flow.expiresIn * 1000);
  }

  function copyCode() {
    navigator.clipboard.writeText(userCode);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  return (
    <div className="fixed inset-0 bg-background flex items-center justify-center p-4 z-50">
      <div className="w-full max-w-md">
        {/* Logo */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-text-primary tracking-tight">KnowHub</h1>
          <p className="text-sm text-text-secondary mt-2">
            Memory & Knowledge Management for AI Agents
          </p>
        </div>

        {/* Card */}
        <div className="bg-surface border border-border rounded-xl p-6">
          <h2 className="text-lg font-semibold text-text-primary mb-4">Sign in</h2>

          {/* Server URL (shared) */}
          <div className="mb-4">
            <label className="block text-xs font-medium text-text-secondary mb-1.5">
              Server URL
            </label>
            <div className="relative">
              <Globe size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
              <input
                type="url"
                value={serverUrl}
                onChange={(e) => setServerUrl(e.target.value)}
                placeholder="https://git.example.com/api/v3"
                className="w-full pl-9 pr-3 py-2 bg-surface-elevated border border-border rounded-md text-sm text-text-primary placeholder:text-text-muted focus:outline-none focus:border-accent"
              />
            </div>
          </div>

          {/* Mode tabs */}
          <div className="flex gap-1 mb-4 p-0.5 bg-background rounded-lg border border-border-light">
            <button
              onClick={() => setMode("token")}
              className={`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${
                mode === "token"
                  ? "bg-surface-elevated text-text-primary"
                  : "text-text-secondary hover:text-text-primary"
              }`}
            >
              Token
            </button>
            <button
              onClick={() => setMode("device")}
              className={`flex-1 py-1.5 text-xs font-medium rounded-md transition-colors ${
                mode === "device"
                  ? "bg-surface-elevated text-text-primary"
                  : "text-text-secondary hover:text-text-primary"
              }`}
            >
              Device Flow
            </button>
          </div>

          {/* Token mode */}
          {mode === "token" && (
            <form onSubmit={handleTokenLogin}>
              <div className="mb-4">
                <label className="block text-xs font-medium text-text-secondary mb-1.5">
                  Access Token
                </label>
                <div className="relative">
                  <KeyRound size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-text-muted" />
                  <input
                    type="password"
                    value={token}
                    onChange={(e) => setToken(e.target.value)}
                    placeholder="Enter your access token"
                    className="w-full pl-9 pr-3 py-2 bg-surface-elevated border border-border rounded-md text-sm text-text-primary placeholder:text-text-muted focus:outline-none focus:border-accent font-mono"
                    required
                  />
                </div>
              </div>

              <button
                type="submit"
                disabled={loading || !serverUrl || !token}
                className="w-full py-2 bg-accent text-white text-sm font-medium rounded-md hover:bg-accent-hover disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 transition-colors"
              >
                {loading ? (
                  <><Loader2 size={14} className="animate-spin" /> Verifying...</>
                ) : (
                  "Sign in"
                )}
              </button>
            </form>
          )}

          {/* Device flow mode */}
          {mode === "device" && !userCode && (
            <div>
              <p className="text-sm text-text-secondary mb-4">
                Sign in through your browser. A verification code will be displayed for you to confirm.
              </p>
              <button
                onClick={handleStartDeviceFlow}
                disabled={loading || !serverUrl}
                className="w-full py-2 bg-accent text-white text-sm font-medium rounded-md hover:bg-accent-hover disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 transition-colors"
              >
                {loading ? (
                  <><Loader2 size={14} className="animate-spin" /> Starting...</>
                ) : (
                  "Start Device Flow"
                )}
              </button>
            </div>
          )}

          {/* Device flow: show code */}
          {mode === "device" && userCode && (
            <div className="text-center">
              <p className="text-sm text-text-secondary mb-3">
                Open the verification URL and enter this code:
              </p>
              <div className="flex items-center justify-center gap-2 mb-4">
                <code className="text-2xl font-mono font-bold text-accent tracking-widest bg-background px-4 py-2 rounded-lg border border-border">
                  {userCode}
                </code>
                <button
                  onClick={copyCode}
                  className="p-2 text-text-secondary hover:text-text-primary transition-colors"
                  title="Copy code"
                >
                  {copied ? <CheckCircle size={16} className="text-success" /> : <Copy size={16} />}
                </button>
              </div>
              <a
                href={verificationUri}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex items-center gap-1 text-sm text-accent hover:text-accent-hover transition-colors"
              >
                Open verification page <ExternalLink size={12} />
              </a>
              {polling && (
                <div className="flex items-center justify-center gap-2 mt-4 text-sm text-text-secondary">
                  <Loader2 size={14} className="animate-spin" />
                  Waiting for confirmation...
                </div>
              )}
            </div>
          )}

          {/* Error */}
          {error && (
            <p className="mt-3 text-sm text-error">{error}</p>
          )}
        </div>

        <p className="text-center text-xs text-text-muted mt-4">
          Connect to any GitHub-compatible git service
        </p>
      </div>
    </div>
  );
}
