import { useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { ChevronLeft, Pencil } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";

interface Props {
  pageName: string;
  onNameChange?: (name: string) => void;
  onSaveDraft: () => void;
  onPublish: () => void;
  saving: boolean;
  isDirty: boolean;
}

export default function ToolBar({
  pageName,
  onNameChange,
  onSaveDraft,
  onPublish,
  saving,
  isDirty,
}: Props) {
  const navigate = useNavigate();

  return (
    <div className="flex items-center gap-2 px-4 py-2 border-b-2 border-border shrink-0">
      <button
        onClick={() => navigate("/")}
        className="text-muted-foreground hover:text-foreground transition-colors flex items-center gap-1 text-xs uppercase tracking-wider"
      >
        <ChevronLeft className="h-3.5 w-3.5" />
        Pages
      </button>

      <span className="text-muted-foreground/30 text-xs">│</span>

      <PageNameField pageName={pageName} onNameChange={onNameChange} />

      {isDirty && (
        <span className="text-[10px] text-muted-foreground/50">●</span>
      )}

      <div className="flex-1" />

      <Button variant="outline" onClick={onSaveDraft} disabled={saving}>
        Save Draft
      </Button>
      <Button onClick={onPublish} disabled={saving}>
        Publish
      </Button>
    </div>
  );
}


function PageNameField({
  pageName,
  onNameChange,
}: {
  pageName: string;
  onNameChange?: (name: string) => void;
}) {
  const [editing, setEditing] = useState(!pageName || !!onNameChange);
  const inputRef = useRef<HTMLInputElement>(null);

  if (editing || onNameChange) {
    return (
      <Input
        ref={inputRef}
        value={pageName}
        onChange={(e) => onNameChange?.(e.target.value)}
        onBlur={() => { if (pageName) setEditing(false); }}
        onKeyDown={(e) => { if (e.key === "Enter" && pageName) setEditing(false); }}
        placeholder="page-name"
        className="font-mono w-36 h-6 text-xs border-0 bg-transparent px-1"
        autoFocus
      />
    );
  }

  return (
    <button
      onClick={() => setEditing(true)}
      className="flex items-center gap-1 font-mono text-xs font-semibold hover:text-primary transition-colors cursor-pointer"
    >
      {pageName}
      <Pencil className="w-2.5 h-2.5 text-muted-foreground" />
    </button>
  );
}
