import { useEffect, useState } from "react";
import { api, BrandData, BrandProductData } from "../api/haixun";
import { Badge, Button, Card, ErrorText, Field, Input, PageTitle, Textarea } from "../components/ui";
import { shortText } from "../lib/format";

export function BrandsPage() {
  const [brands, setBrands] = useState<BrandData[]>([]);
  const [selected, setSelected] = useState<BrandData | null>(null);
  const [products, setProducts] = useState<BrandProductData[]>([]);

  const [displayName, setDisplayName] = useState("");
  const [brief, setBrief] = useState("");
  const [newBrandName, setNewBrandName] = useState("");

  const [newProduct, setNewProduct] = useState({ label: "", product_context: "", match_tags: "", placement_url: "" });
  const [editingProductId, setEditingProductId] = useState<string | null>(null);

  const [message, setMessage] = useState("");
  const [error, setError] = useState<unknown>();
  const [loading, setLoading] = useState(false);
  const [savingProduct, setSavingProduct] = useState(false);

  function applyBrandToForm(brand: BrandData) {
    setDisplayName(brand.display_name || "");
    setBrief(brand.brief || "");
  }

  async function loadProducts(brandId: string) {
    const prodRes = await api.listBrandProducts(brandId);
    setProducts(prodRes.list || []);
  }

  async function load(nextId?: string) {
    setError(undefined);
    try {
      const data = await api.brands();
      const list = data.list || [];
      setBrands(list);

      const next = list.find((b) => b.id === (nextId || selected?.id)) || list[0] || null;
      setSelected(next);

      if (next) {
        applyBrandToForm(next);
        await loadProducts(next.id);
      } else {
        setProducts([]);
        setDisplayName("");
        setBrief("");
      }
    } catch (err) {
      setError(err);
    }
  }

  useEffect(() => {
    void load();
  }, []);

  async function createBrand() {
    setError(undefined);
    setMessage("");
    try {
      const created = await api.createBrand({ display_name: newBrandName || "新品牌" });
      setMessage("品牌已建立");
      setNewBrandName("");
      setBrands((prev) => [...prev, created]);
      setSelected(created);
      applyBrandToForm(created);
      await loadProducts(created.id);
    } catch (err) {
      setError(err);
    }
  }

  async function saveBrand() {
    if (!selected) return;

    const name = displayName.trim();
    if (!name) {
      setError(new Error("牌子名稱不可為空白"));
      return;
    }

    setLoading(true);
    setError(undefined);
    setMessage("");
    try {
      const updated = await api.updateBrand(selected.id, {
        display_name: name,
        brief: brief.trim(),
      });
      setSelected(updated);
      setBrands((prev) => prev.map((b) => (b.id === updated.id ? { ...b, ...updated } : b)));
      applyBrandToForm(updated);
      setMessage("牌子資料已儲存");
    } catch (err) {
      setError(err);
    } finally {
      setLoading(false);
    }
  }

  async function deleteCurrentBrand() {
    if (!selected) return;
    if (!window.confirm("確定刪除此品牌？刪除後無法復原。")) return;
    try {
      await api.deleteBrand(selected.id);
      setMessage("品牌已刪除");
      await load();
    } catch (err) {
      setError(err);
    }
  }

  async function saveProduct() {
    if (!selected) return;

    const label = newProduct.label.trim();
    const productContext = newProduct.product_context.trim();
    if (!label || !productContext) {
      setError(new Error("產品標籤與產品上下文為必填"));
      return;
    }

    const tags = newProduct.match_tags
      ? newProduct.match_tags.split(/[,\s，]+/).filter(Boolean)
      : [];
    const placementUrl = newProduct.placement_url.trim();

    setSavingProduct(true);
    setError(undefined);
    setMessage("");
    try {
      if (editingProductId) {
        const updated = await api.updateBrandProduct(selected.id, editingProductId, {
          label,
          product_context: productContext,
          match_tags: tags,
          placement_url: placementUrl,
        });
        setProducts((prev) => prev.map((p) => (p.id === editingProductId ? updated : p)));
        setMessage("產品已更新");
      } else {
        const p = await api.createBrandProduct(selected.id, {
          label,
          product_context: productContext,
          match_tags: tags,
          placement_url: placementUrl,
        });
        setProducts((prev) => [...prev, p]);
        setMessage("產品已新增");
      }
      setNewProduct({ label: "", product_context: "", match_tags: "", placement_url: "" });
      setEditingProductId(null);
    } catch (err) {
      setError(err);
    } finally {
      setSavingProduct(false);
    }
  }

  function startEditProduct(p: BrandProductData) {
    setEditingProductId(p.id);
    setNewProduct({
      label: p.label,
      product_context: p.product_context,
      match_tags: (p.match_tags || []).join(", "),
      placement_url: p.placement_url || "",
    });
    setMessage(`正在編輯產品：${p.label}`);
    setError(undefined);
  }

  function cancelEditProduct() {
    setEditingProductId(null);
    setNewProduct({ label: "", product_context: "", match_tags: "", placement_url: "" });
  }

  async function removeProduct(pid: string) {
    if (!selected) return;
    if (!window.confirm("刪除此產品？")) return;
    try {
      await api.deleteBrandProduct(selected.id, pid);
      setProducts((prev) => prev.filter((p) => p.id !== pid));
      if (editingProductId === pid) cancelEditProduct();
      setMessage("產品已刪除");
    } catch (err) {
      setError(err);
    }
  }

  function selectBrand(b: BrandData) {
    setSelected(b);
    applyBrandToForm(b);
    setEditingProductId(null);
    setNewProduct({ label: "", product_context: "", match_tags: "", placement_url: "" });
    setMessage("");
    setError(undefined);
    void loadProducts(b.id).catch((err) => setError(err));
  }

  return (
    <div className="page-grid">
      <PageTitle
        title="品牌"
        subtitle="僅管理品牌（牌子）與產品。知識圖譜、掃描、找 TA 策略與外展請至「找 TA」頁操作。"
        action={<Button onClick={() => void load()}>重新載入</Button>}
      />
      <ErrorText error={error} />
      {message ? <Card><pre style={{ whiteSpace: "pre-wrap", margin: 0 }}>{message}</pre></Card> : null}

      <Card title="品牌列表">
        <div className="page-grid">
          <div className="button-row">
            <Input
              value={newBrandName}
              onChange={(e) => setNewBrandName(e.target.value)}
              placeholder="輸入牌子名稱"
            />
            <Button variant="primary" onClick={() => void createBrand()}>建立品牌</Button>
          </div>

          <div className="grid-2">
            {brands.length === 0 && <p className="muted">尚未建立任何品牌。</p>}
            {brands.map((b) => (
              <button
                key={b.id}
                type="button"
                className="card"
                style={{
                  textAlign: "left",
                  cursor: "pointer",
                  border: b.id === selected?.id ? "2px solid var(--hx-brand)" : undefined,
                }}
                onClick={() => selectBrand(b)}
              >
                <div className="button-row" style={{ justifyContent: "space-between" }}>
                  <strong>{b.display_name || b.topic_name || b.id}</strong>
                  <Badge variant={b.id === selected?.id ? "brand" : "neutral"}>
                    {b.seed_query ? "已設定" : "待設定"}
                  </Badge>
                </div>
                <p className="muted">{shortText(b.brief || b.product_context || "", 90)}</p>
              </button>
            ))}
          </div>

          {selected && (
            <div style={{ marginTop: "0.5rem" }}>
              <Button variant="danger" onClick={() => void deleteCurrentBrand()}>
                刪除目前品牌
              </Button>
            </div>
          )}
        </div>
      </Card>

      <Card title="牌子資料">
        {selected ? (
          <div className="page-grid" style={{ maxWidth: "520px" }}>
            <Field label="牌子名稱">
              <Input
                value={displayName}
                onChange={(e) => setDisplayName(e.target.value)}
                placeholder="品牌顯示名稱"
              />
            </Field>

            <Field label="品牌摘要">
              <Textarea
                value={brief}
                onChange={(e) => setBrief(e.target.value)}
                placeholder="簡單描述這個品牌（選填）"
                rows={3}
              />
            </Field>

            <div className="button-row">
              <Button variant="primary" loading={loading} onClick={() => void saveBrand()}>
                儲存牌子
              </Button>
            </div>
          </div>
        ) : (
          <p className="muted">請從上方選擇或建立一個品牌。</p>
        )}
      </Card>

      <Card title="產品">
        {selected ? (
          <>
            <div style={{ marginBottom: "1.25rem" }}>
              {editingProductId ? (
                <p className="muted hx-text-sm" style={{ margin: "0 0 0.75rem" }}>
                  編輯模式：修改下方欄位後按「更新產品」
                </p>
              ) : null}
              <div className="page-grid" style={{ gap: "1rem" }}>
                <div className="grid-2">
                  <Field label="產品標籤">
                    <Input
                      value={newProduct.label}
                      onChange={(e) => setNewProduct((p) => ({ ...p, label: e.target.value }))}
                      placeholder="例如：主力商品"
                    />
                  </Field>
                  <Field label="產品上下文">
                    <Input
                      value={newProduct.product_context}
                      onChange={(e) =>
                        setNewProduct((p) => ({ ...p, product_context: e.target.value }))
                      }
                      placeholder="產品賣點與使用情境"
                    />
                  </Field>
                </div>

                <div className="grid-2">
                  <Field label="置入網址（選填）">
                    <Input
                      value={newProduct.placement_url}
                      onChange={(e) =>
                        setNewProduct((p) => ({ ...p, placement_url: e.target.value }))
                      }
                      placeholder="https://... 置入連結 / 官網 / 產品頁"
                    />
                  </Field>
                  <Field label="Match Tags（選填，空白或逗號分隔）">
                    <Input
                      value={newProduct.match_tags}
                      onChange={(e) =>
                        setNewProduct((p) => ({ ...p, match_tags: e.target.value }))
                      }
                      placeholder="tag1, tag2"
                    />
                  </Field>
                </div>
              </div>

              <div className="button-row" style={{ marginTop: "0.75rem", gap: "0.75rem" }}>
                <Button variant="primary" loading={savingProduct} onClick={() => void saveProduct()}>
                  {editingProductId ? "更新產品" : "新增產品"}
                </Button>
                {editingProductId && (
                  <Button variant="ghost" onClick={cancelEditProduct}>取消編輯</Button>
                )}
              </div>
            </div>

            <div className="table-wrap">
              <table>
                <thead>
                  <tr>
                    <th>標籤</th>
                    <th>上下文</th>
                    <th>置入網址</th>
                    <th>Tags</th>
                    <th style={{ width: "110px" }}>操作</th>
                  </tr>
                </thead>
                <tbody>
                  {products.map((p) => (
                    <tr key={p.id} style={p.id === editingProductId ? { background: "var(--hx-surface-soft, rgba(0,0,0,0.03))" } : undefined}>
                      <td><strong>{p.label}</strong></td>
                      <td>{shortText(p.product_context, 80)}</td>
                      <td>
                        {p.placement_url ? (
                          <a href={p.placement_url} target="_blank" rel="noreferrer" style={{ color: "var(--hx-brand)" }}>
                            {shortText(p.placement_url, 36)}
                          </a>
                        ) : (
                          <span className="subtle">—</span>
                        )}
                      </td>
                      <td>
                        {(p.match_tags || []).map((t) => (
                          <Badge key={t} variant="neutral">{t}</Badge>
                        ))}
                      </td>
                      <td>
                        <div className="button-row" style={{ gap: "0.35rem" }}>
                          <Button onClick={() => startEditProduct(p)}>編輯</Button>
                          <Button variant="danger" onClick={() => void removeProduct(p.id)}>
                            刪除
                          </Button>
                        </div>
                      </td>
                    </tr>
                  ))}
                  {products.length === 0 && (
                    <tr>
                      <td colSpan={5} className="muted">尚未新增產品</td>
                    </tr>
                  )}
                </tbody>
              </table>
            </div>
          </>
        ) : (
          <p className="muted">請先選擇品牌，即可管理產品。</p>
        )}
      </Card>
    </div>
  );
}