import { useEffect, useRef, useState } from "react";
import { useDetailsBackLayer } from "../../app/useBackLayer.js";
import { useI18n } from "../../shared/I18nProvider.jsx";
import { useOutsideDismiss } from "../../shared/hooks/useOutsideDismiss.js";
import { MoreIcon } from "../../shared/ActionIcons.jsx";
import { setupErrorMessage } from "../setup/setup-errors.js";

export function QueuedMessageList({ messages = [], pendingAction, canSteer = false, onEdit, onSteer, onDelete }) {
  const { t } = useI18n();
  const [actionError, setActionError] = useState("");
  const queueIdentity = messages.map((item) => item.id).join("|");
  useEffect(() => setActionError(""), [queueIdentity]);
  const runAction = async (operation) => { setActionError(""); try { await operation(); } catch (error) { setActionError(setupErrorMessage(error, "queue_action_failed")); } };
  return <section className="queued-messages" aria-label={t("conversation.queuedMessages")}>
    {messages.map((item) => <QueuedMessage key={item.id} item={item} pendingAction={pendingAction} canSteer={canSteer} onEdit={onEdit} onSteer={onSteer} onDelete={onDelete} runAction={runAction} t={t} />)}
    {actionError && <p className="queued-action-error">{actionError}</p>}
  </section>;
}

function QueuedMessage({ item, pendingAction, canSteer, onEdit, onSteer, onDelete, runAction, t }) {
  const menuRef = useRef(null);
  useDetailsBackLayer(menuRef, "queued-message-menu");
  const pending = pendingAction?.id === item.id;
  const canSteerItem = canSteer && (item.attachments?.length ?? 0) === 0 && (item.skills?.length ?? 0) === 0;
  const closeMenu = () => { if (menuRef.current?.open) menuRef.current.open = false; };
  useOutsideDismiss(menuRef, closeMenu);
  return <article className="queued-message"><p>{item.text}</p><details className="queued-message-menu" ref={menuRef}><summary aria-label={t("conversation.queuedActions")}><MoreIcon /></summary><div className="queued-message-popover"><button type="button" disabled={pending} onClick={() => { closeMenu(); void runAction(() => onEdit(item)); }}>{t("conversation.editMessage")}</button>{canSteerItem && <button type="button" disabled={pending} onClick={() => { closeMenu(); void runAction(() => onSteer(item.id)); }}>{pending && pendingAction.kind === "steer" ? t("conversation.steering") : t("conversation.sendAsSteer")}</button>}<button type="button" className="queued-cancel" disabled={pending} onClick={() => { closeMenu(); void runAction(() => onDelete(item.id)); }}>{pending && pendingAction.kind === "delete" ? t("conversation.canceling") : t("conversation.cancelMessage")}</button></div></details></article>;
}
