"use client";

import { useState } from "react";
import type { RewriteTone } from "@slackwsh/contracts";
import { api, ApiError } from "../lib/api";
import type { RichTextEditorHandle } from "./RichTextEditor";

const TONES: Array<{ id: RewriteTone; label: string }> = [
  { id: "professional", label: "Professional" },
  { id: "friendly", label: "Friendly" },
  { id: "concise", label: "Concise" },
  { id: "formal", label: "Formal" },
  { id: "casual", label: "Casual" },
];

export function ComposerRewriteBar({
  editorRef,
  draftText,
  onApplied,
}: {
  editorRef: React.RefObject<RichTextEditorHandle | null>;
  draftText: string;
  onApplied?: (text: string) => void;
}) {
  const [tone, setTone] = useState<RewriteTone>("professional");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function run() {
    const current = editorRef.current?.getValue().text.trim() || draftText.trim();
    if (!current || busy) return;
    setBusy(true);
    setError(null);
    try {
      const result = await api.rewriteMessage({ text: current, tone, mode: "rewrite" });
      editorRef.current?.setPlainText(result.text);
      onApplied?.(result.text);
    } catch (err) {
      const message =
        err instanceof ApiError && err.body && typeof err.body === "object" && "message" in err.body
          ? String((err.body as { message: unknown }).message)
          : err instanceof Error
            ? err.message
            : "Rewrite failed";
      setError(message);
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="composer-rewrite">
      <label className="composer-rewrite-tone">
        <select value={tone} disabled={busy} onChange={(e) => setTone(e.target.value as RewriteTone)} aria-label="Rewrite tone">
          {TONES.map((option) => (
            <option key={option.id} value={option.id}>
              {option.label}
            </option>
          ))}
        </select>
      </label>
      <button className="composer-rewrite-btn" type="button" disabled={busy || !draftText.trim()} onClick={() => void run()}>
        {busy ? "Working…" : "Rewrite"}
      </button>
      {error && <span className="composer-rewrite-error" role="alert">{error}</span>}
    </div>
  );
}
