import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { ReplyComposer, type ReplySelection } from "../../components/studio/ReplyComposer";
import { Badge, Button, Card, EmptyState } from "../../components/ui";
import { useData, useRepos } from "../../data/DataContext";
import type { MentionItem, Persona, ThreadsAccount } from "../../domain/types";
import { useI18n } from "../../i18n/I18nContext";
import { allowHttpUrl } from "../../lib/externalUrl";
import { isPersonaReady } from "../../lib/personaPrompt";
import { formatLocalDateTime } from "../../lib/time";

type Props = {
  accountId: string;
  personaId: string;
  accounts: ThreadsAccount[];
  personas: Persona[];
};

export function MentionsPanel({ accountId, personaId, accounts, personas }: Props) {
  const repos = useRepos();
  const { refresh, tick } = useData();
  const { t } = useI18n();
  const [items, setItems] = useState<MentionItem[]>([]);
  const [selById, setSelById] = useState<Record<string, ReplySelection>>({});
  const [composeOpen, setComposeOpen] = useState<Record<string, boolean>>({});
  const [busy, setBusy] = useState("");
  const [message, setMessage] = useState("");
  const [error, setError] = useState("");

  useEffect(() => {
    void repos.mentions.list(accountId || undefined).then(setItems);
  }, [accountId, repos.mentions, tick]);

  function getSel(id: string): ReplySelection {
    return selById[id] || { accountId, personaId };
  }

  function openCompose(id: string) {
    setComposeOpen((m) => ({ ...m, [id]: true }));
    setSelById((m) => ({
      ...m,
      [id]: m[id] || { accountId, personaId },
    }));
  }

  async function sync() {
    if (!accountId) {
      setMessage(t("mentions.needAccount"));
      return;
    }
    setBusy("sync");
    setMessage("");
    setError("");
    try {
      const list = await repos.mentions.sync(accountId);
      setItems(list);
      setMessage(t("mentions.syncDone", { n: list.length }));
      refresh();
    } catch (e) {
      setError(e instanceof Error ? e.message : t("mentions.syncFail"));
    } finally {
      setBusy("");
    }
  }

  async function gen(id: string) {
    const sel = getSel(id);
    if (!isPersonaReady(personas.find((p) => p.id === sel.personaId))) {
      setMessage(t("mentions.needPersona"));
      return;
    }
    setBusy(id);
    setMessage("");
    setError("");
    try {
      const next = await repos.mentions.generateReply(id, sel.personaId);
      setItems((list) => list.map((m) => (m.id === next.id ? next : m)));
      setComposeOpen((m) => ({ ...m, [id]: true }));
    } catch (e) {
      setError(e instanceof Error ? e.message : t("mentions.fail"));
    } finally {
      setBusy("");
    }
  }

  async function reply(id: string, text?: string) {
    setBusy(`s:${id}`);
    setMessage("");
    setError("");
    try {
      const next = await repos.mentions.markReplied(id, text);
      setItems((list) => list.map((m) => (m.id === next.id ? next : m)));
      setMessage(t("mentions.marked"));
      setComposeOpen((m) => ({ ...m, [id]: false }));
      refresh();
    } catch (e) {
      setError(e instanceof Error ? e.message : t("mentions.fail"));
    } finally {
      setBusy("");
    }
  }

  async function skip(id: string) {
    setError("");
    try {
      const next = await repos.mentions.skip(id);
      setItems((list) => list.map((m) => (m.id === next.id ? next : m)));
      refresh();
    } catch (e) {
      setError(e instanceof Error ? e.message : t("mentions.fail"));
    }
  }

  const pending = items.filter((m) => m.status === "pending").length;

  return (
    <div className="hb-stack">
      <div className="hb-wizard-actions" style={{ justifyContent: "space-between", flexWrap: "wrap" }}>
        <p className="text-muted" style={{ fontSize: "var(--hb-text-sm)", margin: 0 }}>
          {t("mentions.hint", { n: pending })}
          {" · "}
          <Link to="/app/scout">{t("mentions.scoutLink")}</Link>
        </p>
        <Button
          type="button"
          variant="secondary"
          disabled={!accountId || busy === "sync"}
          onClick={() => void sync()}
        >
          {busy === "sync" ? t("mentions.syncing") : t("mentions.sync")}
        </Button>
      </div>
      {message ? (
        <p className="hb-banner-ok" role="status">
          {message}
        </p>
      ) : null}
      {error ? (
        <p className="hb-banner-error" role="alert">
          {error}
        </p>
      ) : null}
      {items.length === 0 ? (
        <EmptyState
          title={t("mentions.empty")}
          description={accountId ? t("mentions.emptyHint") : t("mentions.needAccount")}
        />
      ) : (
        items.map((m) => (
          <Card key={m.id}>
            <div className="hb-inline-badges" style={{ marginBottom: "0.4rem" }}>
              <Badge
                tone={
                  m.status === "pending" ? "warning" : m.status === "replied" ? "success" : "neutral"
                }
              >
                {m.status === "pending"
                  ? t("mentions.status.pending")
                  : m.status === "replied"
                    ? t("mentions.status.replied")
                    : t("mentions.status.skipped")}
              </Badge>
              <Badge tone="neutral">@{m.from_username}</Badge>
              <span className="text-muted" style={{ fontSize: "var(--hb-text-xs)" }}>
                {formatLocalDateTime(m.created_at)}
              </span>
            </div>
            <p className="text-muted" style={{ fontSize: "var(--hb-text-xs)", margin: "0 0 0.35rem" }}>
              {m.context_snippet}
              {allowHttpUrl(m.permalink) ? (
                <>
                  {" · "}
                  <a href={allowHttpUrl(m.permalink) ?? undefined} target="_blank" rel="noreferrer">
                    {t("mentions.openThread")}
                  </a>
                </>
              ) : null}
            </p>
            <p style={{ marginTop: 0 }}>{m.text}</p>
            {m.status === "pending" && !composeOpen[m.id] ? (
              <div className="hb-wizard-actions">
                <Button type="button" variant="ghost" onClick={() => openCompose(m.id)}>
                  {t("mentions.reply")}
                </Button>
                <Button type="button" variant="ghost" onClick={() => void skip(m.id)}>
                  {t("mentions.skip")}
                </Button>
              </div>
            ) : null}
            {m.status === "pending" && composeOpen[m.id] ? (
              <ReplyComposer
                accounts={accounts}
                personas={personas}
                selection={getSel(m.id)}
                onSelectionChange={(s) => setSelById((map) => ({ ...map, [m.id]: s }))}
                text={m.draft_text || ""}
                onTextChange={(txt) =>
                  setItems((list) => list.map((x) => (x.id === m.id ? { ...x, draft_text: txt } : x)))
                }
                onGenerate={() => void gen(m.id)}
                onSend={() => void reply(m.id, m.draft_text)}
                generating={busy === m.id}
                sending={busy === `s:${m.id}`}
                label={t("mentions.draftLabel")}
                showAccount={false}
                actionLabel={t("mentions.markReplied")}
                actionBusyLabel={t("mentions.markingReplied")}
              />
            ) : null}
            {m.status === "replied" && m.draft_text ? (
              <p className="text-muted" style={{ fontSize: "var(--hb-text-sm)" }}>
                {t("mentions.repliedPrefix", { text: m.draft_text })}
              </p>
            ) : null}
          </Card>
        ))
      )}
    </div>
  );
}
