"use client";

import { useQuery } from "@tanstack/react-query";
import { useAtomValue, useSetAtom } from "jotai";
import { usePathname, useRouter, useSearchParams, useSelectedLayoutSegment } from "next/navigation";
import { type ClipboardEvent, type KeyboardEvent, useEffect, useId, useRef } from "react";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/cn";
import { WorkflowStatusPill } from "@/modules/ee/workflows/components/workflow-status-pill";
import { useWorkflowBuilder } from "@/modules/ee/workflows/hooks/use-workflow-builder";
import { getWorkflow } from "@/modules/ee/workflows/lib/api-client";
import { workflowKeys } from "@/modules/ee/workflows/lib/query";
import { setWorkflowNameAtom, workflowAtom, workflowNameAtom } from "@/modules/ee/workflows/state/editor";
import { Skeleton } from "@/modules/ui/components/skeleton";

interface WorkflowPageTitleProps {
  workflowId: string;
  isReadOnly: boolean;
}

// Mirrors the PATCH contract (`name: z.string().min(1).max(120)`) so the title input can't author a
// value the API would reject. Keep in sync with ZPatchWorkflowInput in packages/workflows.
const WORKFLOW_NAME_MAX_LENGTH = 120;

// The header bar renders server-side while the workflow is still being fetched client-side. Without
// a placeholder the name slot collapses, so the bar reads as blank and the pill jumps in later.
const WorkflowPageTitleSkeleton = () => (
  <span className="flex h-9 items-center gap-x-3">
    <Skeleton className="h-6 w-56 rounded-md" />
    <Skeleton className="h-5 w-16 rounded-full" />
  </span>
);

// Prefers the atom state hydrated by the builder. On a fresh load of a sub-route like /runs the
// builder never mounts to hydrate the atom, so fetch the name directly; the query stays disabled
// once the atom carries a name, so the builder page never double-fetches.
//
// On the edit tab the title doubles as the name editor: it binds to the draft atom and is
// persisted by the page-level autosave, with Enter committing it immediately. A workflow arriving
// from the dialog-less create flow (?new=1) gets the title focused and selected so the user names
// it immediately.
export const WorkflowPageTitle = ({ workflowId, isReadOnly }: Readonly<WorkflowPageTitleProps>) => {
  const { t } = useTranslation();
  const segment = useSelectedLayoutSegment();
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const workflow = useAtomValue(workflowAtom);
  const workflowName = useAtomValue(workflowNameAtom);
  const setWorkflowName = useSetAtom(setWorkflowNameAtom);
  const inputRef = useRef<HTMLTextAreaElement>(null);
  const hasAutoFocusedRef = useRef(false);
  const nameErrorId = useId();
  const isNew = searchParams.get("new") === "1";
  // Actions and atom state only — the builder page owns the load and the debounced autosave.
  const { save } = useWorkflowBuilder({ workflowId, isReadOnly, loadOnMount: false });

  // Scoped to sub-routes like /runs, where no builder mounts to hydrate the atom. On the edit tab
  // this used to race the builder's own load: whichever landed first won, and the query usually
  // did — painting the plain-text title, then swapping in the editable one a moment later.
  // Waiting for the single source keeps the header still and drops a duplicate GET.
  const { data } = useQuery({
    queryKey: workflowKeys.detail(workflowId),
    queryFn: ({ signal }) => getWorkflow(workflowId, signal),
    enabled: segment !== null && !workflow?.name,
  });

  // Only the edit tab mounts the builder that hydrates (and saves) the draft name; metadata is
  // editable in every status except archived — the same gate as canEditMetadata in the builder.
  const isEditable = segment === null && Boolean(workflow) && !isReadOnly && workflow?.status !== "archived";

  useEffect(() => {
    if (!isNew || !isEditable || hasAutoFocusedRef.current) return;
    hasAutoFocusedRef.current = true;
    inputRef.current?.focus();
    inputRef.current?.select();
    // Consume the one-shot flag so a reload or shared link doesn't re-select the title.
    const nextParams = new URLSearchParams(searchParams);
    nextParams.delete("new");
    const query = nextParams.toString();
    router.replace(query ? `${pathname}?${query}` : pathname, { scroll: false });
  }, [isNew, isEditable, searchParams, router, pathname]);

  // Enter commits the rename instead of doing nothing: the field blurs so the title reads as
  // settled, and the draft is flushed right away rather than waiting out the autosave debounce,
  // which turns the header's "All changes saved" pill into the confirmation.
  // The field stays one line in the header bar (fixed height, no wrapping); field-sizing grows its
  // width with the text where supported, `cols` approximates it elsewhere.

  const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
    // An IME (Japanese/Chinese/Korean) uses Enter to accept the highlighted candidate, so
    // committing there would blur mid-composition and persist a half-typed name. The synthetic
    // event doesn't carry isComposing; the native one does.
    if (event.key !== "Enter" || event.nativeEvent.isComposing) return;
    event.preventDefault();
    // The PATCH contract requires a name, so an empty field keeps focus for an in-place fix;
    // save() is still called either way because it owns both the error and the success feedback.
    if (workflowName.trim()) inputRef.current?.blur();
    void save();
  };

  // maxLength would cut a multi-line paste before its line breaks collapse, so collapse them first
  // and fit the result into the room left around the selection. A single-line paste that fits is
  // left to the browser, which keeps it on the undo stack. Otherwise the rest of the name is
  // untouched, a cut never splits a surrogate pair (an emoji), and a paste where nothing fits
  // does nothing rather than deleting the selection.
  const handlePaste = (event: ClipboardEvent<HTMLTextAreaElement>) => {
    const field = event.currentTarget;
    const { selectionStart, selectionEnd, value } = field;
    const room = WORKFLOW_NAME_MAX_LENGTH - (value.length - (selectionEnd - selectionStart));
    const pasted = event.clipboardData.getData("text/plain");
    const normalized = pasted.replaceAll(/[\r\n]+/g, " ");
    if (normalized === pasted && pasted.length <= room) return;

    event.preventDefault();
    let text = normalized.slice(0, Math.max(room, 0));
    if (/[\uD800-\uDBFF]$/.test(text)) text = text.slice(0, -1);
    if (!text) return;
    field.setRangeText(text, selectionStart, selectionEnd, "end");
    setWorkflowName(field.value);
  };

  const resolved = workflow ?? data;
  if (!resolved) return <WorkflowPageTitleSkeleton />;

  // An empty name blocks every save (buildWorkflowPatch bails before any request). Surface that on
  // the field itself instead of only in the validation-problems dialog, so clearing the pre-selected
  // title isn't a silent dead end.
  const showNameError = isEditable && workflowName.trim().length === 0;

  return (
    // One line inside the editor's h-14 header bar (ED8): name, status pill, and the empty-name error.
    <span className="flex min-w-0 items-center gap-x-3">
      <span className="flex min-w-0 items-center gap-x-2">
        {isEditable ? (
          <textarea
            ref={inputRef}
            rows={1}
            value={workflowName}
            // A name is one line: Enter commits (handleKeyDown), pastes are normalized before they are
            // fitted (handlePaste), and any other line break (e.g. a drop) becomes a space.
            onChange={(event) => setWorkflowName(event.target.value.replaceAll(/[\r\n]+/g, " "))}
            onPaste={handlePaste}
            onKeyDown={handleKeyDown}
            aria-label={t("common.workflow_name")}
            placeholder={t("common.workflow_name")}
            maxLength={WORKFLOW_NAME_MAX_LENGTH}
            aria-invalid={showNameError || undefined}
            aria-describedby={showNameError ? nameErrorId : undefined}
            // Approximates content width where field-sizing is unsupported (Firefox).
            cols={Math.max(workflowName.length, 12)}
            className={cn(
              "h-9 min-w-0 rounded-md bg-transparent px-2 py-1.5 leading-6",
              "text-base font-semibold text-slate-900 placeholder:font-normal placeholder:text-slate-400",
              // Sizes to its content where supported, up to the room the header bar leaves beside the
              // controls; a longer name is cut off rather than wrapping out of the bar.
              "[field-sizing:content] max-w-72 resize-none overflow-hidden whitespace-nowrap lg:max-w-md",
              // Dashed hover/focus box, matching the dashboard's editable title
              // (see dashboard-page-header.tsx): slate while hovered, brand while editing.
              "border border-dashed border-transparent transition-colors",
              "hover:border-slate-300 focus:border-brand-dark",
              // Same specificity means source order decides, and Tailwind emits hover last — without
              // this the border drops back to slate when the pointer rests on a focused field.
              "focus:hover:border-brand-dark",
              "focus:ring-0 focus:outline-none",
              // Red box while the name is empty, matching the amber "Not saved" pill and the inline error.
              showNameError &&
                "border-red-300 hover:border-red-400 focus:border-red-400 focus:hover:border-red-400"
            )}
          />
        ) : (
          <span className="min-w-0 truncate px-2 text-base font-semibold text-slate-900">
            {resolved.name}
          </span>
        )}
        <WorkflowStatusPill status={resolved.status} size="normal" />
      </span>
      {showNameError ? (
        <span id={nameErrorId} role="alert" className="truncate text-xs font-medium text-red-600">
          {t("workspace.workflows.validation_problem_name_missing")}
        </span>
      ) : null}
    </span>
  );
};
