import { useEffect, useState } from "react";
import { useRepos } from "../../data/DataContext";
import type { Brand, BrandProduct, ManualImportItem, ManualImportResult } from "../../domain/types";
import { useI18n } from "../../i18n/I18nContext";
import { useFormatApiError } from "../../lib/apiErrors";
import { parseCsvRows } from "../../lib/csv";
import { Badge, Button, Input, Textarea } from "../ui";
import type { BadgeTone } from "../ui";

type Row = { url: string; text: string; author: string };

const MAX_ROWS = 20;
const emptyRow = (): Row => ({ url: "", text: "", author: "" });

function statusTone(status: ManualImportResult["status"]): BadgeTone {
  switch (status) {
    case "qualified":
      return "success";
    case "rejected":
      return "danger";
    case "skipped":
      return "neutral";
    default:
      return "danger";
  }
}

/** 把貼上的 CSV 文字解析成匯入列；有 url/text 表頭就照表頭找欄，沒有就假設 url,text,author 順序。 */
function parsePastedCsv(raw: string): Row[] {
  const rows = parseCsvRows(raw);
  if (rows.length === 0) return [];
  const header = rows[0].map((h) => h.trim().toLowerCase());
  const hasHeader = header.includes("url");
  const colUrl = hasHeader ? header.indexOf("url") : 0;
  const colText = hasHeader ? header.indexOf("text") : 1;
  const colAuthor = hasHeader ? header.indexOf("author") : 2;
  const dataRows = hasHeader ? rows.slice(1) : rows;
  return dataRows
    .map((r) => ({
      url: (r[colUrl] || "").trim(),
      text: (colText >= 0 ? r[colText] : "")?.trim() || "",
      author: (colAuthor >= 0 ? r[colAuthor] : "")?.trim() || "",
    }))
    .filter((r) => r.url || r.text);
}

/**
 * 手動匯入商機（demand-radar spec §4.11 P1）：貼 Threads／Facebook 貼文網址＋內文，
 * 或貼 CSV 批次，走跟自動巡一樣的五問判定。沒有爬蟲能讀任意網址的內文，判定一律吃
 * 使用者貼上的文字，這是「不承諾全平台自動抓取」前提下的合規補位（不是偷懶）。
 */
export function ManualImportPanel({ onImported }: { onImported: () => void }) {
  const { t } = useI18n();
  const repos = useRepos();
  const formatError = useFormatApiError();
  const [rows, setRows] = useState<Row[]>([emptyRow()]);
  const [csvOpen, setCsvOpen] = useState(false);
  const [csvText, setCsvText] = useState("");
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");
  const [results, setResults] = useState<ManualImportResult[] | null>(null);
  const [brands, setBrands] = useState<Brand[]>([]);
  const [products, setProducts] = useState<BrandProduct[]>([]);
  const [brandId, setBrandId] = useState("");
  const [productId, setProductId] = useState("");
  const scout = (repos as unknown as { scout?: { listBrands: () => Promise<Brand[]>; listProducts: (id: string) => Promise<BrandProduct[]> } }).scout;
  useEffect(() => { if (scout) void scout.listBrands().then(setBrands).catch(() => setBrands([])); }, [scout]);
  useEffect(() => { if (!scout || !brandId) { setProducts([]); return; } void scout.listProducts(brandId).then(setProducts).catch(() => setProducts([])); }, [scout, brandId]);

  function updateRow(i: number, patch: Partial<Row>) {
    setRows((prev) => prev.map((r, idx) => (idx === i ? { ...r, ...patch } : r)));
  }

  function addRow() {
    setRows((prev) => (prev.length >= MAX_ROWS ? prev : [...prev, emptyRow()]));
  }

  function removeRow(i: number) {
    setRows((prev) => (prev.length <= 1 ? prev : prev.filter((_, idx) => idx !== i)));
  }

  function applyCsv() {
    const parsed = parsePastedCsv(csvText);
    if (parsed.length === 0) {
      setErr(t("radar.import.csvEmpty"));
      return;
    }
    setRows(parsed.slice(0, MAX_ROWS).map((r) => ({ url: r.url, text: r.text, author: r.author })));
    setErr("");
    setCsvOpen(false);
    setCsvText("");
  }

  async function submit() {
    const items: ManualImportItem[] = rows
      .map((r) => ({ url: r.url.trim(), text: r.text.trim(), author: r.author.trim() || undefined }))
      .filter((it) => it.url || it.text);
    if (items.length === 0) {
      setErr(t("radar.import.needRow"));
      return;
    }
    if (scout && (!brandId || !productId)) {
      setErr(t("radar.import.needProduct"));
      return;
    }
    setBusy(true);
    setErr("");
    setResults(null);
    try {
      const res = scout
        ? await repos.radar.importOpportunities(items, { brand_id: brandId || undefined, product_id: productId || undefined })
        : await repos.radar.importOpportunities(items);
      setResults(res.results);
      if (res.results.some((r) => r.status === "qualified" || r.status === "rejected")) {
        onImported();
      }
    } catch (e) {
      setErr(formatError(e));
    } finally {
      setBusy(false);
    }
  }

  return (
    <div className="hb-radar-section hb-radar-import">
      <h3 className="hb-radar-section__title">{t("radar.import.title")}</h3>
      <p className="hb-radar-section__hint">{t("radar.import.hint")}</p>
      {brands.length ? <div className="hb-radar-actions"><label>{t("radar.inbox.brand")}<select value={brandId} onChange={(e) => { setBrandId(e.target.value); setProductId(""); }}><option value="">{t("radar.explore.pickBrand")}</option>{brands.map((b) => <option key={b.id} value={b.id}>{b.display_name}</option>)}</select></label><label>{t("radar.inbox.product")}<select value={productId} disabled={!brandId} onChange={(e) => setProductId(e.target.value)}><option value="">{t("radar.explore.pickProduct")}</option>{products.map((p) => <option key={p.id} value={p.id}>{p.label}</option>)}</select></label></div> : null}

      <div className="hb-radar-actions">
        <Button type="button" variant="ghost" onClick={() => setCsvOpen((v) => !v)}>
          {csvOpen ? t("radar.import.csvClose") : t("radar.import.csvOpen")}
        </Button>
      </div>

      {csvOpen ? (
        <div className="hb-radar-import__csv">
          <Textarea
            name="radar-import-csv"
            label={t("radar.import.csvLabel")}
            hint={t("radar.import.csvHint")}
            rows={5}
            value={csvText}
            onChange={(e) => setCsvText(e.target.value)}
          />
          <div className="hb-radar-actions">
            <Button type="button" variant="secondary" onClick={applyCsv}>
              {t("radar.import.csvApply")}
            </Button>
          </div>
        </div>
      ) : null}

      {rows.map((row, i) => (
        <div className="hb-radar-import__row" key={i}>
          <Input
            name={`radar-import-url-${i}`}
            label={t("radar.import.url")}
            placeholder="https://www.threads.net/@handle/post/..."
            value={row.url}
            onChange={(e) => updateRow(i, { url: e.target.value })}
          />
          <Textarea
            name={`radar-import-text-${i}`}
            label={t("radar.import.text")}
            rows={2}
            value={row.text}
            onChange={(e) => updateRow(i, { text: e.target.value })}
          />
          <Input
            name={`radar-import-author-${i}`}
            label={t("radar.import.author")}
            placeholder="@handle"
            value={row.author}
            onChange={(e) => updateRow(i, { author: e.target.value })}
          />
          {rows.length > 1 ? (
            <Button type="button" variant="ghost" onClick={() => removeRow(i)}>
              {t("radar.import.removeRow")}
            </Button>
          ) : null}
        </div>
      ))}

      <div className="hb-radar-actions">
        <Button type="button" variant="ghost" onClick={addRow} disabled={rows.length >= MAX_ROWS}>
          {t("radar.import.addRow")}
        </Button>
        <Button type="button" onClick={() => void submit()} disabled={busy}>
          {busy ? t("radar.import.submitting") : t("radar.import.submit")}
        </Button>
      </div>

      {err ? (
        <p className="hb-banner-error" role="alert">
          {err}
        </p>
      ) : null}

      {results ? (
        <ul className="hb-radar-import__results">
          {results.map((r, i) => (
            <li key={`${r.url}-${i}`} className="hb-radar-import__result">
              <Badge tone={statusTone(r.status)}>{t(`radar.import.status.${r.status}`)}</Badge>
              <span className="hb-radar-import__resultUrl">{r.url}</span>
              {r.intent_band ? (
                <span className="hb-radar-section__hint">
                  {t(`radar.today.band.${r.intent_band}`)} · {r.intent_score}
                </span>
              ) : null}
              {r.error ? <span className="hb-radar-section__hint">{r.error}</span> : null}
            </li>
          ))}
        </ul>
      ) : null}
    </div>
  );
}
