import React, { useState, useEffect } from "react";
import type { Project, Session, Phase } from "../types";
import { formatSessionLabel } from "../utils/timeFormat";

const api = window.api;

type Theme = "dark" | "light";

interface HeaderProps {
  projects: Project[];
  sessions: Session[];
  selectedProject: Project | null;
  selectedSession: Session | null;
  onSelectProject: (project: Project | null) => void;
  onSelectSession: (session: Session | null) => void;
  onCreateProject: () => void;
  onCreateSession: () => void;
  onDeleteProject?: (id: string) => void;
  onDeleteSession?: (id: string) => void;
  onRenameSession?: (id: string, name: string) => void;
  theme: Theme;
  onToggleTheme: () => void;
  gitBranch: string | null;
  onOpenSettings: () => void;
}

const phaseLabels: Record<Phase, string> = {
  research: "Research",
  plan: "Plan",
  implement: "Implement",
};

const phases: Phase[] = ["research", "plan", "implement"];

export function Header({
  projects,
  sessions,
  selectedProject,
  selectedSession,
  onSelectProject,
  onSelectSession,
  onCreateProject,
  onCreateSession,
  onDeleteProject,
  onDeleteSession,
  onRenameSession,
  theme,
  onToggleTheme,
  gitBranch,
  onOpenSettings,
}: HeaderProps) {
  const handleDeleteProject = () => {
    if (!selectedProject || !onDeleteProject) return;
    if (confirm(`Delete project "${selectedProject.name}"? This cannot be undone.`)) {
      onDeleteProject(selectedProject.id);
    }
  };

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

  const [isRenamingSession, setIsRenamingSession] = useState(false);
  const [renameValue, setRenameValue] = useState("");
  // Guard against double-commit (onKeyDown Enter → unmount → onBlur)
  const renameCommitted = React.useRef(false);

  const startRename = () => {
    if (!selectedSession) return;
    renameCommitted.current = false;
    setRenameValue(selectedSession.name);
    setIsRenamingSession(true);
  };

  const commitRename = () => {
    if (renameCommitted.current) return;
    renameCommitted.current = true;
    if (selectedSession && onRenameSession && renameValue.trim()) {
      onRenameSession(selectedSession.id, renameValue.trim());
    }
    setIsRenamingSession(false);
  };

  const cancelRename = () => {
    renameCommitted.current = true; // prevent blur from committing after cancel
    setIsRenamingSession(false);
  };

  // ── Maximize ─────────────────────────────────────────────────
  const [isMaximized, setIsMaximized] = useState(false);

  useEffect(() => {
    // Returns the unsubscribe function; React cleanup calls it on unmount.
    // On macOS, clicking the native green traffic light also fires this,
    // keeping the glyph accurate when native controls are used.
    return api.onWindowMaximized(setIsMaximized);
  }, []);

  // ── Branch copy ──────────────────────────────────────────────
  const [copied, setCopied] = useState(false);

  const handleCopyBranch = () => {
    if (!gitBranch) return;
    navigator.clipboard.writeText(gitBranch);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  return (
    <header className="header">
      <div className="header-left">
        {/* ── Wordmark ── */}
        <span className="app-wordmark">Claude Flow</span>

        <select
          value={selectedProject?.id || ""}
          onChange={(e) => {
            const project = projects.find((p) => p.id === e.target.value);
            onSelectProject(project || null);
            onSelectSession(null);
          }}
        >
          <option value="">Select Project...</option>
          {projects.map((p) => (
            <option key={p.id} value={p.id}>
              {p.name}
            </option>
          ))}
        </select>
        <button onClick={onCreateProject}>+ Project</button>
        {selectedProject && onDeleteProject && (
          <button
            onClick={handleDeleteProject}
            className="btn-delete"
            title="Delete project"
          >
            🗑️
          </button>
        )}

        {selectedProject && (
          <>
            {isRenamingSession ? (
              <input
                autoFocus
                value={renameValue}
                onChange={(e) => setRenameValue(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === "Enter") commitRename();
                  if (e.key === "Escape") cancelRename();
                }}
                onBlur={commitRename}
                className="session-rename-input"
              />
            ) : (
              <select
                value={selectedSession?.id || ""}
                onChange={(e) => {
                  const session = sessions.find((s) => s.id === e.target.value);
                  onSelectSession(session || null);
                }}
              >
                <option value="">Select Session...</option>
                {sessions.map((s) => (
                  <option key={s.id} value={s.id}>
                    {formatSessionLabel(s.name, s.updated_at)}
                  </option>
                ))}
              </select>
            )}
            <button onClick={onCreateSession}>+ Session</button>
            {selectedSession &&
              onRenameSession &&
              !isRenamingSession &&
              selectedSession.phase !== "implement" && (
                <button
                  onClick={startRename}
                  className="btn-rename"
                  title="Rename session"
                >
                  ✏️
                </button>
              )}
            {selectedSession && onDeleteSession && (
              <button
                onClick={handleDeleteSession}
                className="btn-delete"
                title="Delete session"
              >
                🗑️
              </button>
            )}
          </>
        )}
      </div>

      <div className="header-right">
        {selectedSession && (
          <div className="phase-indicator">
            {phases.map((phase) => {
              const phaseIndex = phases.indexOf(phase);
              const currentIndex = phases.indexOf(selectedSession.phase);
              const isComplete = phaseIndex < currentIndex;
              const isActive = phase === selectedSession.phase;

              return (
                <span
                  key={phase}
                  className={`phase-step ${isActive ? "active" : ""} ${
                    isComplete ? "complete" : ""
                  }`}
                >
                  {phaseLabels[phase]}
                </span>
              );
            })}
          </div>
        )}

        {/* ── Branch badge ── */}
        {selectedSession && gitBranch && (
          <button
            className={["branch-badge", copied ? "branch-copied" : ""]
              .filter(Boolean)
              .join(" ")}
            onClick={handleCopyBranch}
            title={copied ? "Copied!" : `Click to copy: ${gitBranch}`}
          >
            ⎇ {gitBranch}
          </button>
        )}

        {/* ── Theme toggle ── */}
        <button className="theme-toggle" onClick={onToggleTheme}>
          {theme === "dark" ? "[light]" : "[dark]"}
        </button>

        {/* ── Maximize toggle ── */}
        <button
          className="maximize-btn"
          onClick={() => api.toggleMaximize()}
          title={isMaximized ? "Restore window" : "Maximize window"}
        >
          {isMaximized ? '⊡' : '□'}
        </button>

        {/* ── Settings button ── */}
        <button className="settings-btn" onClick={onOpenSettings} title="Settings">
          &#9881;
        </button>
      </div>
    </header>
  );
}
