"use client";

import { useState, useRef, useEffect } from "react";
import { useAuth } from "@/lib/auth";

export function AuthButton({ onViewProfile }: { onViewProfile?: (handle: string) => void }) {
  const { isAuthenticated, isLoading, session, login, logout } = useAuth();
  const [showModal, setShowModal] = useState(false);
  const [showDropdown, setShowDropdown] = useState(false);
  const [handle, setHandle] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [error, setError] = useState("");
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Close dropdown on outside click
  useEffect(() => {
    if (!showDropdown) return;

    const handleClickOutside = (e: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(e.target as Node)
      ) {
        setShowDropdown(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [showDropdown]);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!handle.trim()) return;

    setIsSubmitting(true);
    setError("");

    try {
      await login(handle.trim());
    } catch (err) {
      setError(err instanceof Error ? err.message : "Login failed");
      setIsSubmitting(false);
    }
  };

  const handleLogout = async () => {
    setShowDropdown(false);
    await logout();
  };

  if (isLoading) {
    return (
      <div className="w-4 h-4 rounded-full border-2 border-zinc-200 border-t-zinc-400 animate-spin" />
    );
  }

  if (isAuthenticated && session) {
    return (
      <div className="relative" ref={dropdownRef}>
        <button
          onClick={() => setShowDropdown((prev) => !prev)}
          className="flex items-center gap-2 px-3 py-1.5 rounded-full hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors cursor-pointer"
        >
          {session.avatar ? (
            /* eslint-disable-next-line @next/next/no-img-element */
            <img
              src={session.avatar}
              alt={session.handle}
              width={24}
              height={24}
              className="rounded-full"
            />
          ) : (
            <div className="w-6 h-6 rounded-full bg-emerald-100 dark:bg-emerald-950 flex items-center justify-center text-[11px] text-emerald-700 dark:text-emerald-400 font-medium">
              {(session.displayName || session.handle).charAt(0).toUpperCase()}
            </div>
          )}
          <span className="text-sm text-zinc-600 dark:text-zinc-400 max-w-[100px] truncate">
            {session.displayName || session.handle}
          </span>
        </button>

        {showDropdown && (
          <div className="absolute right-0 top-full mt-2 w-44 bg-white dark:bg-zinc-900 rounded-xl shadow-xl border border-zinc-100 dark:border-zinc-700 py-2 z-50">
            <button
              onClick={() => {
                if (onViewProfile) {
                  onViewProfile(session.handle);
                  setShowDropdown(false);
                } else {
                  window.open(session.did ? `https://www.impactindexer.org/data?did=${session.did}` : "#", "_blank");
                }
              }}
              className="block w-full text-left px-3 py-1.5 text-xs text-zinc-400 dark:text-zinc-400 truncate hover:text-emerald-600 dark:hover:text-emerald-400 transition-colors cursor-pointer"
            >
              @{session.handle}
            </button>
            <div className="h-px bg-zinc-100 dark:border-zinc-800 my-1" />
            <button
              onClick={handleLogout}
              className="flex items-center gap-2 w-full px-3 py-1.5 text-xs text-zinc-600 dark:text-zinc-400 hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors cursor-pointer"
            >
              <svg
                className="w-3.5 h-3.5 text-zinc-400"
                fill="none"
                viewBox="0 0 24 24"
                strokeWidth={1.5}
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M8.25 9V5.25A2.25 2.25 0 0 1 10.5 3h6a2.25 2.25 0 0 1 2.25 2.25v13.5A2.25 2.25 0 0 1 16.5 21h-6a2.25 2.25 0 0 1-2.25-2.25V15m-3 0-3-3m0 0 3-3m-3 3H15"
                />
              </svg>
              Sign out
            </button>
          </div>
        )}
      </div>
    );
  }

  return (
    <>
      <button
        onClick={() => setShowModal(true)}
        className="px-4 py-1.5 text-sm font-medium text-zinc-600 dark:text-zinc-400 rounded-full hover:text-zinc-900 dark:hover:text-zinc-100 hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors cursor-pointer whitespace-nowrap"
      >
        Sign in
      </button>

      {showModal && (
        <div
          className="fixed inset-0 z-50 flex items-start justify-center pt-[20vh]"
          onClick={() => setShowModal(false)}
        >
          {/* Backdrop */}
          <div className="absolute inset-0 bg-black/20 backdrop-blur-sm" />

          {/* Modal */}
          <div
            className="relative w-full max-w-sm mx-4 bg-white dark:bg-zinc-900 rounded-xl shadow-lg border border-zinc-200 dark:border-zinc-700 p-6"
            onClick={(e) => e.stopPropagation()}
          >
            <h2 className="text-lg font-semibold text-zinc-900 dark:text-zinc-100 mb-1">
              Sign in with ATProto
            </h2>
            <p className="text-sm text-zinc-400 dark:text-zinc-400 mb-5">
              Enter your Bluesky handle to connect.
            </p>

            <form onSubmit={handleLogin}>
              <label
                htmlFor="auth-handle"
                className="block text-sm text-zinc-600 dark:text-zinc-400 mb-1.5"
              >
                Handle
              </label>
              <input
                id="auth-handle"
                type="text"
                value={handle}
                onChange={(e) => setHandle(e.target.value)}
                placeholder="alice.bsky.social"
                disabled={isSubmitting}
                autoFocus
                className="w-full px-3 py-2 text-sm bg-white dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 rounded-lg
                           placeholder:text-zinc-300 dark:placeholder:text-zinc-500
                           focus:outline-none focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-400
                           disabled:opacity-50 disabled:cursor-not-allowed text-zinc-900 dark:text-zinc-100"
              />
              <p className="text-xs text-zinc-300 dark:text-zinc-500 mt-1.5">
                Just a username? We&apos;ll add .bsky.social for you.
              </p>

              {error && <p className="text-sm text-red-500 mt-2">{error}</p>}

              <div className="flex gap-2 mt-5">
                <button
                  type="button"
                  onClick={() => setShowModal(false)}
                  disabled={isSubmitting}
                  className="flex-1 px-3 py-2 text-sm text-zinc-600 dark:text-zinc-400 bg-zinc-50 dark:bg-zinc-800 rounded-lg
                             hover:bg-zinc-100 dark:hover:bg-zinc-700 transition-colors
                             disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={isSubmitting || !handle.trim()}
                  className="flex-1 px-3 py-2 text-sm text-white bg-emerald-600 rounded-lg
                             hover:bg-emerald-700 transition-colors
                             disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isSubmitting ? "Connecting..." : "Connect"}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </>
  );
}
