import React, { useState, useRef } from "react";
import type { Project, Session } from "../types";
import { formatRelativeTime } from "../utils/timeFormat";

interface SidebarProps {
  projects: Project[];
  sessions: Session[];
  selectedProject: Project | null;
  selectedSession: Session | null;
  onSelectProject: (project: Project) => void;
  onSelectSession: (session: Session | null) => void;
  onCreateProject: () => void;
  onCreateSession: (projectId: string) => void;
  onDeleteProject: (id: string) => void;
  onDeleteSession: (id: string) => void;
  onRenameSession: (id: string, name: string) => void;
  loadingBySession: Record<string, boolean>;
  width: number;
  collapsed: boolean;
  onCollapsedChange: (collapsed: boolean) => void;
}

export function Sidebar({
  projects,
  sessions,
  selectedProject,
  selectedSession,
  onSelectProject,
  onSelectSession,
  onCreateProject,
  onCreateSession,
  onDeleteProject,
  onDeleteSession,
  onRenameSession,
  loadingBySession,
  width,
  collapsed,
  onCollapsedChange,
}: SidebarProps) {
  const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null);
  const [renameValue, setRenameValue] = useState("");
  // Guard against double-commit (onKeyDown Enter → unmount → onBlur)
  const renameCommitted = useRef(false);

  const startRename = (session: Session) => {
    renameCommitted.current = false;
    setRenameValue(session.name);
    setRenamingSessionId(session.id);
  };

  const commitRename = (sessionId: string) => {
    if (renameCommitted.current) return;
    renameCommitted.current = true;
    const trimmed = renameValue.trim();
    if (trimmed) onRenameSession(sessionId, trimmed);
    setRenamingSessionId(null);
  };

  const cancelRename = () => {
    renameCommitted.current = true;
    setRenamingSessionId(null);
  };

  const handleDeleteProject = (project: Project) => {
    if (confirm(`Delete project "${project.name}"? This cannot be undone.`)) {
      onDeleteProject(project.id);
    }
  };

  const handleDeleteSession = (session: Session) => {
    if (confirm(`Delete session "${session.name}"? This cannot be undone.`)) {
      onDeleteSession(session.id);
    }
  };

  if (collapsed) {
    return (
      <div className="sidebar collapsed">
        <button
          className="sidebar-collapse-btn"
          onClick={() => onCollapsedChange(false)}
          title="Expand sidebar"
        >
          ▶
        </button>
      </div>
    );
  }

  return (
    <div className="sidebar" style={{ width }}>
      {/* ── Header ── */}
      <div className="sidebar-header">
        <span className="sidebar-title">Projects</span>
        <div className="sidebar-header-actions">
          <button
            className="sidebar-action-btn"
            onClick={onCreateProject}
            title="Add project"
          >
            +
          </button>
          <button
            className="sidebar-collapse-btn"
            onClick={() => onCollapsedChange(true)}
            title="Collapse sidebar"
          >
            ◁
          </button>
        </div>
      </div>

      {/* ── Tree ── */}
      <div className="sidebar-tree">
        {projects.length === 0 && (
          <div className="sidebar-empty">No projects yet</div>
        )}

        {projects.map((project) => {
          const projectSessions = sessions.filter(
            (s) => s.project_id === project.id
          );
          const isSelectedProject = selectedProject?.id === project.id;

          return (
            <React.Fragment key={project.id}>
              {/* Project row */}
              <div
                className={`project-item${isSelectedProject ? " selected" : ""}`}
              >
                <span
                  className="project-name"
                  onClick={() => {
                    onSelectProject(project);
                    onSelectSession(null);
                  }}
                  title={project.path}
                >
                  {project.name}
                </span>
                <div className="item-controls">
                  <button
                    className="item-btn"
                    onClick={() => onCreateSession(project.id)}
                    title="New session"
                  >
                    +
                  </button>
                  <button
                    className="item-btn item-btn-danger"
                    onClick={() => handleDeleteProject(project)}
                    title="Delete project"
                  >
                    ×
                  </button>
                </div>
              </div>

              {/* Empty sessions hint (only under selected project) */}
              {projectSessions.length === 0 && isSelectedProject && (
                <div className="sidebar-empty session-empty">
                  No sessions yet
                </div>
              )}

              {/* Session rows */}
              {projectSessions.map((session) => {
                const isSelected = selectedSession?.id === session.id;
                const isLoading = loadingBySession[session.id] ?? false;
                const isRenaming = renamingSessionId === session.id;

                return (
                  <div
                    key={session.id}
                    className={`session-item${isSelected ? " selected" : ""}`}
                  >
                    {isRenaming ? (
                      <input
                        className="session-rename-input"
                        autoFocus
                        value={renameValue}
                        onChange={(e) => setRenameValue(e.target.value)}
                        onKeyDown={(e) => {
                          if (e.key === "Enter") commitRename(session.id);
                          if (e.key === "Escape") cancelRename();
                        }}
                        onBlur={() => commitRename(session.id)}
                      />
                    ) : (
                      <>
                        <span
                          className="session-name"
                          onClick={() => onSelectSession(session)}
                          title={`${session.name} · ${session.phase} · ${formatRelativeTime(session.updated_at)}`}
                        >
                          {session.name}
                          {isLoading && (
                            <span
                              className="session-activity-dot"
                              title="Thinking…"
                            />
                          )}
                        </span>
                        <div className="item-controls">
                          <button
                            className="item-btn"
                            onClick={() => startRename(session)}
                            title="Rename session"
                          >
                            ✏️
                          </button>
                          <button
                            className="item-btn item-btn-danger"
                            onClick={() => handleDeleteSession(session)}
                            title="Delete session"
                          >
                            ×
                          </button>
                        </div>
                      </>
                    )}
                  </div>
                );
              })}
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
}
