"use client";

import { useState } from "react";
import { formatDistanceToNow } from "date-fns";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useAlertConfirm } from "@/components/ui/alert-dialog";
import type { AgentThread } from "@/lib/agents/threads";

interface AgentThreadRailProps {
  threads: AgentThread[];
  activeThreadId: string | null;
  onSelectThread: (threadId: string) => void;
  onNewThread: () => void;
  onRenameThread: (threadId: string, title: string) => void;
  onDeleteThread: (threadId: string) => void;
}

function relativeTime(iso: string): string {
  try {
    return formatDistanceToNow(new Date(iso), { addSuffix: false }) + " ago";
  } catch {
    return "";
  }
}

export function AgentThreadRail({
  threads,
  activeThreadId,
  onSelectThread,
  onNewThread,
  onRenameThread,
  onDeleteThread,
}: AgentThreadRailProps) {
  const [openMenuId, setOpenMenuId] = useState<string | null>(null);
  const [renamingId, setRenamingId] = useState<string | null>(null);
  const [renameDraft, setRenameDraft] = useState("");
  const { confirm: confirmAlert, AlertConfirmPortal } = useAlertConfirm();

  function startRename(thread: AgentThread) {
    setRenamingId(thread.id);
    setRenameDraft(thread.title);
    setOpenMenuId(null);
  }

  function commitRename() {
    if (!renamingId) return;
    const title = renameDraft.trim();
    if (title) onRenameThread(renamingId, title);
    setRenamingId(null);
    setRenameDraft("");
  }

  function cancelRename() {
    setRenamingId(null);
    setRenameDraft("");
  }

  async function confirmDelete(thread: AgentThread) {
    setOpenMenuId(null);
    const ok = await confirmAlert({
      title: `Delete thread "${thread.title}"?`,
      description: "This permanently removes the thread. Cannot be undone.",
      actionLabel: "Delete",
      destructive: true,
    });
    if (ok) onDeleteThread(thread.id);
  }

  return (
    <>
    <aside className="w-60 shrink-0 border-r bg-background flex flex-col h-full">
      <div className="px-3 py-3 border-b">
        <div className="flex items-center justify-between mb-2">
          <h3 className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
            Threads
          </h3>
        </div>
        <Button
          type="button"
          variant="outline"
          className="w-full justify-start text-sm"
          onClick={onNewThread}
        >
          + New thread
        </Button>
      </div>

      <div className="flex-1 overflow-y-auto py-2">
        {threads.length === 0 ? (
          <p className="px-3 py-4 text-xs text-muted-foreground leading-relaxed">
            No saved threads yet. Start a conversation to save it here.
          </p>
        ) : (
          <ul className="space-y-0.5 px-2">
            {threads.map((thread) => {
              const isActive = thread.id === activeThreadId;
              const isRenaming = thread.id === renamingId;
              const isMenuOpen = thread.id === openMenuId;
              return (
                <li
                  key={thread.id}
                  className={`group relative rounded-md ${
                    isActive ? "bg-accent" : "hover:bg-accent/50"
                  }`}
                  onContextMenu={(e) => {
                    e.preventDefault();
                    setOpenMenuId(thread.id);
                  }}
                >
                  {isRenaming ? (
                    <div className="px-2 py-1.5">
                      <Input
                        autoFocus
                        value={renameDraft}
                        onChange={(e) => setRenameDraft(e.target.value)}
                        onBlur={commitRename}
                        onKeyDown={(e) => {
                          if (e.key === "Enter") {
                            e.preventDefault();
                            commitRename();
                          } else if (e.key === "Escape") {
                            e.preventDefault();
                            cancelRename();
                          }
                        }}
                        className="h-7 text-sm"
                      />
                    </div>
                  ) : (
                    <button
                      type="button"
                      onClick={() => onSelectThread(thread.id)}
                      className="w-full text-left px-2 py-1.5 pr-7 rounded-md"
                    >
                      <div className="text-sm truncate" title={thread.title}>
                        {thread.title}
                      </div>
                      <div className="text-[10px] text-muted-foreground mt-0.5">
                        {relativeTime(thread.updatedAt)}
                      </div>
                    </button>
                  )}

                  {!isRenaming && (
                    <button
                      type="button"
                      aria-label="Thread actions"
                      onClick={(e) => {
                        e.stopPropagation();
                        setOpenMenuId(isMenuOpen ? null : thread.id);
                      }}
                      className={`absolute right-1 top-1.5 px-1.5 py-0.5 rounded text-xs text-muted-foreground hover:bg-background hover:text-foreground ${
                        isMenuOpen ? "opacity-100" : "opacity-0 group-hover:opacity-100"
                      }`}
                    >
                      ...
                    </button>
                  )}

                  {isMenuOpen && !isRenaming && (
                    <div
                      className="absolute right-1 top-7 z-10 w-32 rounded-md border bg-popover shadow-md py-1 text-sm"
                      onMouseLeave={() => setOpenMenuId(null)}
                    >
                      <button
                        type="button"
                        onClick={() => startRename(thread)}
                        className="w-full text-left px-3 py-1.5 hover:bg-accent"
                      >
                        Rename
                      </button>
                      <button
                        type="button"
                        onClick={() => confirmDelete(thread)}
                        className="w-full text-left px-3 py-1.5 hover:bg-accent text-destructive"
                      >
                        Delete
                      </button>
                    </div>
                  )}
                </li>
              );
            })}
          </ul>
        )}
      </div>
    </aside>
    <AlertConfirmPortal />
    </>
  );
}
