"use client";

import { useState, useRef, useEffect, useCallback } from "react";
import type { GraphNode } from "@/lib/types";
import { PREFIX_COLORS } from "@/lib/types";
import type { BeadsComment } from "@/hooks/useBeadsComments";
import { useIsMobile } from "@/hooks/useIsMobile";

interface CommentTooltipProps {
  node: GraphNode;
  x: number;
  y: number;
  onClose: () => void;
  onSubmit: (text: string) => Promise<void>;
  isAuthenticated: boolean;
  existingComments?: BeadsComment[];
}

export function CommentTooltip({
  node,
  x,
  y,
  onClose,
  onSubmit,
  isAuthenticated,
  existingComments,
}: CommentTooltipProps) {
  const [text, setText] = useState("");
  const [sending, setSending] = useState(false);
  const tooltipRef = useRef<HTMLDivElement>(null);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const [pos, setPos] = useState({ x: 0, y: 0 });
  const [visible, setVisible] = useState(false);
  const isMobile = useIsMobile();

  // Position the tooltip after first render (measure dimensions)
  useEffect(() => {
    if (!tooltipRef.current) return;
    const tt = tooltipRef.current.getBoundingClientRect();
    const vw = window.innerWidth;
    const vh = window.innerHeight;

    let nx = x + 14;
    let ny = y - tt.height - 14;

    // Clamp right
    if (nx + tt.width > vw - 16) nx = vw - tt.width - 16;
    // Clamp left
    if (nx < 16) nx = 16;
    // If overflows top, flip below cursor
    if (ny < 16) ny = y + 28;
    // Clamp bottom
    if (ny + tt.height > vh - 16) ny = vh - tt.height - 16;

    setPos({ x: nx, y: ny });
    setVisible(true);
  }, [x, y]);

  // Auto-focus textarea on mount
  useEffect(() => {
    if (isAuthenticated) {
      // Small delay to let position settle
      const timer = setTimeout(() => textareaRef.current?.focus(), 100);
      return () => clearTimeout(timer);
    }
  }, [isAuthenticated]);

  // Close on Escape
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") onClose();
    };
    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [onClose]);

  // Close on click outside
  useEffect(() => {
    const handleMouseDown = (e: MouseEvent) => {
      if (
        tooltipRef.current &&
        !tooltipRef.current.contains(e.target as Node)
      ) {
        onClose();
      }
    };
    // Use a small delay so the right-click that opened the tooltip doesn't
    // immediately close it
    const timer = setTimeout(() => {
      window.addEventListener("mousedown", handleMouseDown);
    }, 50);
    return () => {
      clearTimeout(timer);
      window.removeEventListener("mousedown", handleMouseDown);
    };
  }, [onClose]);

  const handleSubmit = useCallback(async () => {
    if (!text.trim() || sending) return;
    setSending(true);
    try {
      await onSubmit(text.trim());
      setText("");
    } catch (err) {
      console.error("Failed to post comment:", err);
    } finally {
      setSending(false);
    }
  }, [text, sending, onSubmit]);

  // Handle Ctrl+Enter to submit
  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
        e.preventDefault();
        handleSubmit();
      }
    },
    [handleSubmit]
  );

  const prefixColor = PREFIX_COLORS[node.prefix] || "#a1a1aa";
  const commentCount = existingComments?.length || 0;

  // Shared form content used in both mobile and desktop layouts
  const formContent = (
    <>
      {/* Node info */}
      <div className="mb-3">
        <span className="text-xs font-mono text-emerald-600 dark:text-emerald-400">
          {node.id}
        </span>
        <h3 className="text-sm font-semibold text-zinc-800 dark:text-zinc-200 leading-tight mt-0.5">
          {node.title}
        </h3>
      </div>

      {/* Existing comments preview */}
      {commentCount > 0 && existingComments && (
        <div className="mb-3 pb-3 border-b border-zinc-100 dark:border-zinc-800">
          <div className="flex items-center gap-1.5 mb-2">
            <svg
              className="w-3.5 h-3.5 text-blue-500"
              fill="none"
              viewBox="0 0 24 24"
              strokeWidth={1.5}
              stroke="currentColor"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M12 20.25c4.97 0 9-3.694 9-8.25s-4.03-8.25-9-8.25S3 7.444 3 12c0 2.104.859 4.023 2.273 5.48.432.447.74 1.04.586 1.641a4.483 4.483 0 01-.923 1.785A5.969 5.969 0 006 21c1.282 0 2.47-.402 3.445-1.087.81.22 1.668.337 2.555.337z"
              />
            </svg>
            <span className="text-[10px] font-medium text-zinc-500 dark:text-zinc-400 uppercase tracking-wider">
              {commentCount} comment{commentCount !== 1 ? "s" : ""}
            </span>
          </div>
          {/* Show most recent 2 comments */}
          <div className="space-y-2">
            {existingComments.slice(0, 2).map((comment) => (
              <div key={comment.uri} className="flex gap-1.5">
                <div className="shrink-0 w-4 h-4 rounded-full bg-zinc-100 dark:bg-zinc-800 overflow-hidden mt-0.5">
                  {comment.avatar ? (
                    <img
                      src={comment.avatar}
                      alt=""
                      className="w-full h-full object-cover"
                    />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-[7px] font-medium text-zinc-400 dark:text-zinc-500">
                      {(comment.handle || comment.did)
                        .charAt(0)
                        .toUpperCase()}
                    </div>
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <a
                    href={`https://www.impactindexer.org/data?did=${comment.did}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-[10px] font-medium text-zinc-500 dark:text-zinc-400 hover:text-emerald-600 dark:hover:text-emerald-400 transition-colors"
                  >
                    {comment.displayName || comment.handle}
                  </a>
                  <p className="text-[11px] text-zinc-500 dark:text-zinc-400 line-clamp-2 leading-tight">
                    {comment.text}
                  </p>
                </div>
              </div>
            ))}
            {commentCount > 2 && (
              <p className="text-[10px] text-zinc-400 dark:text-zinc-500 italic">
                +{commentCount - 2} more — see detail panel
              </p>
            )}
          </div>
        </div>
      )}

      {/* Compose area */}
      {isAuthenticated ? (
        <div>
          <textarea
            ref={textareaRef}
            value={text}
            onChange={(e) => setText(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Leave a comment..."
            rows={3}
            className="w-full px-2.5 py-2 text-xs border border-zinc-200 dark:border-zinc-700 rounded-md bg-zinc-50 dark:bg-zinc-800 text-zinc-700 dark:text-zinc-300 placeholder-zinc-400 dark:placeholder-zinc-500 resize-none focus:outline-none focus:ring-1 focus:ring-emerald-500 focus:border-emerald-500"
          />
          <div className="flex items-center justify-between mt-2">
            <span className="text-[10px] text-zinc-300 dark:text-zinc-600">
              {typeof navigator !== "undefined" &&
              navigator.platform?.includes("Mac")
                ? "\u2318"
                : "Ctrl"}
              +Enter to send
            </span>
            <div className="flex items-center gap-2">
              <button
                onClick={onClose}
                className="px-2.5 py-1 text-[11px] text-zinc-400 dark:text-zinc-500 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleSubmit}
                disabled={!text.trim() || sending}
                className="px-3 py-1 text-[11px] font-medium text-white bg-emerald-500 rounded-md hover:bg-emerald-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {sending ? (
                  <span className="flex items-center gap-1">
                    <svg
                      className="w-3 h-3 animate-spin"
                      fill="none"
                      viewBox="0 0 24 24"
                    >
                      <circle
                        className="opacity-25"
                        cx="12"
                        cy="12"
                        r="10"
                        stroke="currentColor"
                        strokeWidth="4"
                      />
                      <path
                        className="opacity-75"
                        fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"
                      />
                    </svg>
                    Sending
                  </span>
                ) : (
                  "Send"
                )}
              </button>
            </div>
          </div>
        </div>
      ) : (
        <div className="text-center py-3">
          <svg
            className="w-5 h-5 text-zinc-300 dark:text-zinc-600 mx-auto mb-1.5"
            fill="none"
            viewBox="0 0 24 24"
            strokeWidth={1.5}
            stroke="currentColor"
          >
            <path
              strokeLinecap="round"
              strokeLinejoin="round"
              d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 002.25-2.25v-6.75a2.25 2.25 0 00-2.25-2.25H6.75a2.25 2.25 0 00-2.25 2.25v6.75a2.25 2.25 0 002.25 2.25z"
            />
          </svg>
          <p className="text-xs text-zinc-400 dark:text-zinc-500">Sign in to comment</p>
        </div>
      )}
    </>
  );

  // Mobile: bottom sheet layout
  if (isMobile) {
    return (
      <>
        <div className="fixed inset-0 z-[99] bg-black/20" onClick={onClose} />
        <div className="fixed inset-x-0 bottom-0 z-[100] bg-white dark:bg-zinc-900 rounded-t-2xl shadow-2xl animate-slide-up-sheet">
          <div className="w-10 h-1 bg-zinc-300 dark:bg-zinc-600 rounded-full mx-auto mt-3 mb-1" />
          <div className="px-4 pb-6 pt-2">
            {formContent}
          </div>
          <div className="h-[env(safe-area-inset-bottom)]" />
        </div>
      </>
    );
  }

  // Desktop: floating tooltip
  return (
    <div
      ref={tooltipRef}
      style={{
        position: "fixed",
        left: pos.x,
        top: pos.y,
        width: 320,
        zIndex: 100,
        opacity: visible ? 1 : 0,
        transform: visible ? "translateY(0)" : "translateY(4px)",
        transition: "opacity 0.2s ease, transform 0.2s ease",
      }}
      className="bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 rounded-lg overflow-hidden"
      onContextMenu={(e) => e.preventDefault()}
    >
      <style>{`
        .comment-tooltip-shadow {
          box-shadow: 0 8px 32px rgba(0,0,0,0.08), 0 2px 8px rgba(0,0,0,0.08);
        }
      `}</style>
      <div className="comment-tooltip-shadow p-[18px_20px]">
        {/* Colored accent bar */}
        <div
          className="rounded-sm mb-2.5"
          style={{
            width: 24,
            height: 2,
            background: prefixColor,
            opacity: 0.6,
          }}
        />
        {formContent}
      </div>
    </div>
  );
}
