import { useEffect, useState } from "react";
import { newId } from "../../../lib/id";
import { speakersOf } from "../../../domain/speakers";
import type { Persona, ThreadsAccount } from "../../../domain/types";
import { Button, Card, Select, Textarea } from "../../../components/ui";
import { useRepos } from "../../../data/DataContext";
import { useI18n } from "../../../i18n/I18nContext";
import { isPersonaReady, personaOptionLabel } from "../../../lib/personaPrompt";
import type { WizardDraft } from "../wizardState";

type Props = {
  draft: WizardDraft;
  accounts: ThreadsAccount[];
  onChange: (partial: Partial<WizardDraft>) => void;
};

export function ScriptStep({ draft, accounts, onChange }: Props) {
  const repos = useRepos();
  const { t } = useI18n();
  const speakers = speakersOf(draft);
  const speakerAccounts = accounts.filter((a) => speakers.includes(a.id) && a.is_usable);
  const [personas, setPersonas] = useState<Persona[]>([]);
  const [personaId, setPersonaId] = useState("");
  const [busyId, setBusyId] = useState("");
  const [aiError, setAiError] = useState("");

  useEffect(() => {
    void (async () => {
      const list = await repos.personas.list();
      const active = await repos.personas.getActiveId();
      setPersonas(list);
      setPersonaId(active || list[0]?.id || "");
    })();
  }, [repos.personas]);

  function updateStep(id: string, patch: { account_id?: string; text?: string }) {
    onChange({
      steps: draft.steps.map((s) => (s.id === id ? { ...s, ...patch } : s)),
    });
  }

  function addReply() {
    const defaultAcc =
      draft.cast_account_ids[0] || draft.lead_account_id || speakerAccounts[0]?.id || "";
    onChange({
      steps: [
        ...draft.steps,
        {
          id: newId("step"),
          sort_order: draft.steps.length,
          kind: "reply",
          account_id: defaultAcc,
          text: "",
          delay_from_previous_sec: draft.interval_minutes * 60,
        },
      ],
    });
  }

  function removeStep(id: string) {
    const step = draft.steps.find((s) => s.id === id);
    if (!step || step.kind === "root") return;
    onChange({ steps: draft.steps.filter((s) => s.id !== id).map((s, i) => ({ ...s, sort_order: i })) });
  }

  async function aiFill(stepId: string) {
    const persona = personas.find((p) => p.id === personaId);
    if (!isPersonaReady(persona)) return;
    setBusyId(stepId);
    setAiError("");
    try {
      const index = draft.steps.findIndex((s) => s.id === stepId);
      const step = draft.steps[index];
      if (!step) return;
      const isRoot = step.kind === "root" || index === 0;
      const prev = index > 0 ? draft.steps[index - 1] : undefined;
      const speaker = accounts.find((a) => a.id === step.account_id);
      const text = await repos.plays.generateStep({
        personaId: persona!.id,
        context: (isRoot ? draft.topic || draft.title : prev?.text || draft.topic || draft.title).trim(),
        topic: draft.topic || draft.title,
        speakerLabel: speaker?.display_name || speaker?.username || t("posts.accountFallback"),
        isLead: step.account_id === draft.lead_account_id,
        mode: isRoot ? "root" : "reply",
      });
      if (!text) throw new Error(t("plays.aiEmptyResult"));
      updateStep(stepId, { text });
    } catch (e) {
      setAiError(e instanceof Error ? e.message : t("plays.aiFail"));
    } finally {
      setBusyId("");
    }
  }

  const ready = isPersonaReady(personas.find((p) => p.id === personaId));

  return (
    <Card title={t("wizard.script.title")}>
      <Select
        label={t("wizard.script.persona")}
        value={personaId}
        onChange={(e) => {
          setPersonaId(e.target.value);
          void repos.personas.setActiveId(e.target.value);
        }}
      >
        {personas.map((p) => (
          <option key={p.id} value={p.id}>
            {personaOptionLabel(p)}
          </option>
        ))}
      </Select>
      {!ready ? (
        <p className="text-muted" style={{ fontSize: "var(--hb-text-sm)", marginTop: "0.5rem" }}>
          {t("wizard.script.personaNotReady")}
        </p>
      ) : null}
      {aiError ? (
        <p className="hb-form-error" role="alert" style={{ fontSize: "var(--hb-text-sm)" }}>
          {aiError}
        </p>
      ) : null}
      <div className="hb-stack" style={{ marginTop: "1rem" }}>
        {draft.steps.map((step, index) => {
          const isRoot = step.kind === "root" || index === 0;
          return (
            <div key={step.id} className="hb-script-row">
              <div className="hb-script-row__head">
                <strong>
                  {isRoot ? t("wizard.script.root") : t("wizard.script.replyN", { n: index })}
                </strong>
                <div className="hb-wizard-actions" style={{ margin: 0 }}>
                  <Button
                    type="button"
                    variant="ghost"
                    disabled={busyId === step.id || !ready}
                    onClick={() => void aiFill(step.id)}
                  >
                    {busyId === step.id ? t("wizard.script.generating") : t("wizard.script.ai")}
                  </Button>
                  {!isRoot ? (
                    <Button type="button" variant="ghost" onClick={() => removeStep(step.id)}>
                      {t("common.delete")}
                    </Button>
                  ) : null}
                </div>
              </div>
              {isRoot ? (
                <p className="text-muted">
                  {t("wizard.script.account", {
                    name:
                      accounts.find((a) => a.id === draft.lead_account_id)?.display_name ||
                      t("wizard.script.noLead"),
                  })}
                </p>
              ) : (
                <Select
                  label={t("wizard.script.speaker")}
                  value={step.account_id}
                  onChange={(e) => updateStep(step.id, { account_id: e.target.value })}
                >
                  {speakerAccounts.map((a) => (
                    <option key={a.id} value={a.id}>
                      {a.display_name}
                      {a.id === draft.lead_account_id ? t("wizard.script.leadTag") : ""}
                    </option>
                  ))}
                </Select>
              )}
              <Textarea
                label={t("wizard.script.text")}
                value={step.text}
                onChange={(e) => updateStep(step.id, { text: e.target.value })}
                placeholder={isRoot ? t("wizard.script.rootPh") : t("wizard.script.replyPh")}
              />
            </div>
          );
        })}
        <Button type="button" variant="ghost" onClick={addReply} disabled={!draft.lead_account_id}>
          {t("wizard.script.addReply")}
        </Button>
      </div>
    </Card>
  );
}
