import { useState } from "react";
import type { ImageDocument } from "@core/document";
import type { SelectionState, ViewportState } from "@editor/state";
import type { GenerateSettings } from "@editor/tools";
import type { AppStore } from "@editor/store";
import { runGenerate } from "../generate/runGenerate";

export type GenerateActionControlsProps = {
  document: ImageDocument;
  selection: SelectionState;
  viewport: ViewportState;
  settings: GenerateSettings;
  dispatch: AppStore["dispatch"];
};

export function GenerateActionControls({ document, selection, viewport, settings, dispatch }: GenerateActionControlsProps) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string>();
  const canGenerate = Boolean(settings.prompt.trim()) && !busy;

  return (
    <div className="flex items-center px-2">
      <button
        type="button"
        disabled={!canGenerate}
        className="h-12 rounded-full bg-white px-7 text-base font-semibold !text-black transition hover:bg-white/90 focus:outline-none focus-visible:ring-2 focus-visible:ring-white/40 disabled:pointer-events-none disabled:opacity-35"
        title={error ?? "Generate with ComfyUI"}
        onClick={() => {
          setBusy(true);
          setError(undefined);
          void runGenerate({ document, selection, viewport, settings, dispatch })
            .catch((reason: unknown) => setError(reason instanceof Error ? reason.message : "Generation failed"))
            .finally(() => setBusy(false));
        }}
      >
        {busy ? "Generating…" : "Generate"}
      </button>
    </div>
  );
}
