import { useEffect, useState } from "react";
import type { BrandProduct, DemandMap, DemandMapPhrase } from "../../domain/types";
import { useI18n } from "../../i18n/I18nContext";
import { Badge, Button, Textarea } from "../ui";

type Category = "pain_phrases" | "scenario_phrases" | "desired_outcomes" | "solution_signals" | "exclusion_signals";
const categories: Array<{ key: Category; labelKey: string; hintKey: string; kind: string }> = [
  { key: "pain_phrases", labelKey: "radar.demand.pain", hintKey: "radar.demand.painHint", kind: "pain" },
  { key: "scenario_phrases", labelKey: "radar.demand.scenario", hintKey: "radar.demand.scenarioHint", kind: "scenario" },
  { key: "desired_outcomes", labelKey: "radar.demand.outcome", hintKey: "radar.demand.outcomeHint", kind: "outcome" },
  { key: "solution_signals", labelKey: "radar.demand.solution", hintKey: "radar.demand.solutionHint", kind: "solution" },
  { key: "exclusion_signals", labelKey: "radar.demand.exclusion", hintKey: "radar.demand.exclusionHint", kind: "exclusion" },
];

type Props = {
  product: BrandProduct;
  map: DemandMap | null;
  loading?: boolean;
  saving?: boolean;
  error?: string;
  onSave: (patch: Omit<DemandMap, "product_id" | "updated_at"> & { expected_map_version: number }) => void;
  onDraftChange?: (patch: DemandMapPatch) => void;
};

export type DemandMapPatch = Omit<DemandMap, "product_id" | "updated_at"> & { expected_map_version: number };

function lines(phrases: DemandMapPhrase[] = []): string {
  return phrases.filter((phrase) => phrase.enabled).map((phrase) => phrase.text).join("\n");
}

function asPhrases(value: string, kind: string, existing: DemandMapPhrase[]): DemandMapPhrase[] {
  return value.split(/\n|,|、/).map((text) => text.trim()).filter(Boolean).map((text) => {
    const old = existing.find((phrase) => phrase.text === text);
    return old ? { ...old, enabled: true } : { text, kind, origin: "user", basis_kind: "custom", basis_text: "custom", enabled: true };
  });
}

function buildPatch(map: DemandMap, draft: Record<Category, string>, custom: string): DemandMapPatch {
  const next = Object.fromEntries(categories.map(({ key, kind }) => [key, asPhrases(draft[key], kind, map[key])])) as Record<Category, DemandMapPhrase[]>;
  return {
    expected_map_version: map.map_version,
    demand_input_version: map.demand_input_version,
    map_version: map.map_version,
    state: next.pain_phrases.length && next.scenario_phrases.length && next.solution_signals.length ? "ready" : "incomplete",
    pain_phrases: next.pain_phrases,
    scenario_phrases: next.scenario_phrases,
    desired_outcomes: next.desired_outcomes,
    solution_signals: next.solution_signals,
    exclusion_signals: next.exclusion_signals,
    source_basis: map.source_basis,
    custom_phrases: asPhrases(custom, "custom", map.custom_phrases),
    ai_enriched_at: map.ai_enriched_at,
  };
}

export function DemandMapEditor({ product, map, loading = false, saving = false, error, onSave, onDraftChange }: Props) {
  const { t } = useI18n();
  const [draft, setDraft] = useState<Record<Category, string>>({
    pain_phrases: "", scenario_phrases: "", desired_outcomes: "", solution_signals: "", exclusion_signals: "",
  });
  const [custom, setCustom] = useState("");

  useEffect(() => {
    if (!map) return;
    setDraft({
      pain_phrases: lines(map.pain_phrases),
      scenario_phrases: lines(map.scenario_phrases),
      desired_outcomes: lines(map.desired_outcomes),
      solution_signals: lines(map.solution_signals),
      exclusion_signals: lines(map.exclusion_signals),
    });
    setCustom(lines(map.custom_phrases));
  }, [map]);

  function save() {
    if (!map) return;
    onSave(buildPatch(map, draft, custom));
  }

  function changeDraft(next: Record<Category, string>) {
    setDraft(next);
    if (map) onDraftChange?.(buildPatch(map, next, custom));
  }

  function changeCustom(next: string) {
    setCustom(next);
    if (map) onDraftChange?.(buildPatch(map, draft, next));
  }

  return (
    <section className="hb-demand-map-editor" aria-label={t("radar.demand.aria", { label: product.label })}>
      <div className="hb-demand-map-editor__head">
        <div>
          <h3>{t("radar.demand.title")}</h3>
          <p className="hb-radar-section__hint">{t("radar.demand.hint")}</p>
        </div>
        {map ? <div className="hb-opp-card__meta"><Badge tone={map.state === "ready" ? "success" : "warning"}>{map.state === "ready" ? t("radar.demand.ready") : t("radar.demand.incomplete")}</Badge><span>{t("radar.demand.version", { n: map.map_version })}</span></div> : null}
      </div>
      {loading ? <p className="hb-radar-section__hint">{t("radar.demand.loading")}</p> : null}
      {error ? <p className="hb-banner-error" role="alert">{error}</p> : null}
      {map ? <>
        {categories.map(({ key, labelKey, hintKey }) => (
          <div className="hb-demand-map-editor__field" key={key}>
            <Textarea
              name={`demand-${key}`}
              label={t(labelKey)}
              hint={t(hintKey)}
              rows={3}
              required={key === "pain_phrases" || key === "scenario_phrases" || key === "solution_signals"}
              value={draft[key]}
              onChange={(event) => changeDraft({ ...draft, [key]: event.target.value })}
            />
            <div className="hb-demand-map-editor__basis">
              {(map[key] ?? []).map((item) => <Badge key={`${key}-${item.text}`} tone={item.origin === "product" ? "brand" : item.origin === "ai" ? "warning" : "neutral"}>{item.origin === "product" ? t("radar.demand.origin.product") : item.origin === "ai" ? t("radar.demand.origin.ai") : t("radar.demand.origin.user")} · {item.text}</Badge>)}
            </div>
          </div>
        ))}
        <Textarea name="demand-custom" label={t("radar.demand.custom")} hint={t("radar.demand.customHint")} rows={2} value={custom} onChange={(event) => changeCustom(event.target.value)} />
        <div className="hb-demand-map-editor__actions"><Button type="button" disabled={saving} onClick={save}>{saving ? t("radar.demand.saving") : t("radar.demand.save")}</Button></div>
      </> : null}
    </section>
  );
}
