import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { useRepos } from "../../data/DataContext";
import type { Opportunity, ReplyVariant, ReplyVariantKind, ThreadsAccount } from "../../domain/types";
import { useI18n } from "../../i18n/I18nContext";
import { useFormatApiError } from "../../lib/apiErrors";
import { Button, Select } from "../ui";

/** 公開留言是主線；其餘版本按需生成，避免一次燒五倍點數（需求決策 #6）。 */
const SECONDARY_VARIANTS: ReplyVariantKind[] = ["dm", "no_sales", "professional", "humorous"];

type Props = {
  opportunity: Opportunity;
  /** 送出或標記後讓上層重讀，卡片狀態才跟得上。 */
  onChanged?: () => void;
};

/**
 * 回覆草稿：產生、複製、標記已送出。
 *
 * 「回什麼」是這條線最花時間的一步，所以它必須待在看到人的地方，
 * 而不是另一個頁面。
 */
export function ReplyComposer({ opportunity, onChanged }: Props) {
  const repos = useRepos();
  const { t } = useI18n();
  const formatError = useFormatApiError();
  const [reply, setReply] = useState<ReplyVariant | undefined>(opportunity.default_reply);
  const [accounts, setAccounts] = useState<ThreadsAccount[]>([]);
  const [accountId, setAccountId] = useState("");
  const [busy, setBusy] = useState("");
  const [error, setError] = useState("");
  const [message, setMessage] = useState("");

  useEffect(() => {
    setReply(opportunity.default_reply);
  }, [opportunity.id, opportunity.default_reply]);

  useEffect(() => {
    void repos.accounts
      .list()
      .then((list) => {
        const usable = list.filter((a) => a.is_usable);
        setAccounts(usable);
        setAccountId((prev) => (prev && usable.some((a) => a.id === prev) ? prev : usable[0]?.id || ""));
      })
      .catch(() => setAccounts([]));
  }, [repos.accounts]);

  async function generate(variant: ReplyVariantKind) {
    setBusy(variant);
    setError("");
    setMessage("");
    try {
      setReply(await repos.radar.createReply(opportunity.id, variant));
      setMessage(t("radar.today.msg.replyReady"));
    } catch (e) {
      setError(formatError(e));
    } finally {
      setBusy("");
    }
  }

  async function copy() {
    if (!reply?.text) return;
    try {
      await navigator.clipboard.writeText(reply.text);
      setMessage(t("radar.today.msg.copied"));
    } catch {
      setError(t("radar.today.msg.copyFail"));
    }
  }

  async function markUsed(channel: "outbox" | "manual_copy") {
    if (!reply?.id) {
      setError(t("radar.today.msg.needReply"));
      return;
    }
    setBusy(`mark-${channel}`);
    setError("");
    setMessage("");
    try {
      const res = await repos.radar.markReplyUsed(
        opportunity.id,
        reply.id,
        channel,
        channel === "outbox" ? accountId : undefined,
      );
      setReply(res.reply);
      setMessage(res.health_advice || t(channel === "outbox" ? "radar.today.msg.sent" : "radar.today.msg.marked"));
      onChanged?.();
    } catch (e) {
      setError(formatError(e));
    } finally {
      setBusy("");
    }
  }

  const isDm = reply?.variant === "dm";
  const canSendOutbox = accounts.length > 0;

  return (
    <div className="hb-reply-variants">
      <p className="hb-radar-section__hint">{t("radar.today.reply.hint")}</p>
      <div className="hb-radar-actions">
        <Button type="button" disabled={Boolean(busy)} onClick={() => void generate("public_comment")}>
          {busy === "public_comment" ? t("radar.today.msg.replyWorking") : t("radar.reply.writeForMe")}
        </Button>
        {SECONDARY_VARIANTS.map((variant) => (
          <Button
            key={variant}
            type="button"
            variant="ghost"
            disabled={Boolean(busy)}
            onClick={() => void generate(variant)}
          >
            {t(`radar.today.reply.variant.${variant}`)}
          </Button>
        ))}
      </div>

      {reply?.text ? (
        <>
          <pre className="radar-card__reply">{reply.text}</pre>
          <div className="hb-radar-actions">
            <Button type="button" variant="secondary" onClick={() => void copy()}>
              {t("radar.today.reply.copy")}
            </Button>
            {reply.used_at ? (
              <span className="hb-radar-section__hint">
                {reply.sent_channel === "outbox" && reply.outbox_id
                  ? t("radar.today.reply.usedOutbox")
                  : t("radar.today.reply.used")}
              </span>
            ) : (
              <>
                <Button
                  type="button"
                  variant="ghost"
                  disabled={busy === "mark-manual_copy"}
                  onClick={() => void markUsed("manual_copy")}
                >
                  {t("radar.today.reply.markCopy")}
                </Button>
                {/* 私訊版一律人工送出：平台沒有合規的自動私訊路徑。 */}
                {!isDm ? (
                  <Button
                    type="button"
                    variant="secondary"
                    disabled={busy === "mark-outbox" || !canSendOutbox}
                    title={canSendOutbox ? undefined : t("radar.today.reply.needAccount")}
                    onClick={() => void markUsed("outbox")}
                  >
                    {t("radar.today.reply.markOutbox")}
                  </Button>
                ) : null}
                {!isDm && !canSendOutbox ? (
                  <span className="hb-radar-section__hint">
                    {t("radar.today.reply.needAccount")} <Link to="/app/crew">{t("nav.crew")}</Link>
                  </span>
                ) : null}
                {!isDm && accounts.length > 1 ? (
                  <Select
                    name={`reply-account-${opportunity.id}`}
                    label={t("radar.reply.sendAs")}
                    value={accountId}
                    onChange={(e) => setAccountId(e.target.value)}
                  >
                    {accounts.map((a) => <option key={a.id} value={a.id}>@{a.username}</option>)}
                  </Select>
                ) : null}
              </>
            )}
          </div>
        </>
      ) : null}

      {error ? <p className="hb-form-error" role="alert">{error}</p> : null}
      {message ? <p className="hb-radar-section__hint" role="status">{message}</p> : null}
    </div>
  );
}
