import { useEffect, useMemo, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { PageHeader } from "../components/layout/PageHeader";
import { Badge, Button, EmptyState, Input, Pager, Textarea } from "../components/ui";
import { useData, useRepos } from "../data/DataContext";
import type { Brand, BrandProduct } from "../domain/types";
import { newId } from "../lib/id";
import { pageSlice } from "../lib/pagination";
import { nowUnixNano } from "../lib/time";
import { useI18n } from "../i18n/I18nContext";

const emptyProductForm = {
  label: "",
  product_context: "",
  pain_points: "",
  match_tags: "",
  provider_capability_terms: "",
  provider_exclude_terms: "",
  placement_url: "",
};

type DetailTab = "brand" | "products";

const BRAND_PAGE = 12;
const PRODUCT_PAGE = 8;

/** 品牌庫：手機橫向選牌 → 下方編輯；桌面左列表右焦點 */
export function BrandsPage() {
  const repos = useRepos();
  const { refresh, tick } = useData();
  const { t } = useI18n();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  const [brands, setBrands] = useState<Brand[]>([]);
  const [products, setProducts] = useState<BrandProduct[]>([]);
  const [brandId, setBrandId] = useState("");
  const [detailTab, setDetailTab] = useState<DetailTab>("brand");
  // 舊 CTA／書籤仍可用，但服務政策已從品牌管理拆成獨立頁。
  useEffect(() => {
    if (searchParams.get("tab") === "serviceProfile") {
      navigate("/app/policy", { replace: true });
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  const [showCreate, setShowCreate] = useState(false);
  const [showProductForm, setShowProductForm] = useState(false);

  const [brandQuery, setBrandQuery] = useState("");
  const [brandPage, setBrandPage] = useState(1);
  const [productQuery, setProductQuery] = useState("");
  const [productPage, setProductPage] = useState(1);

  const [newBrandName, setNewBrandName] = useState("");
  const [editName, setEditName] = useState("");
  const [editBrief, setEditBrief] = useState("");
  const [editAudience, setEditAudience] = useState("");
  const [editGoals, setEditGoals] = useState("");
  const [productForm, setProductForm] = useState(emptyProductForm);
  const [importUrl, setImportUrl] = useState("");
  const [editingProductId, setEditingProductId] = useState<string | null>(null);
  const [busy, setBusy] = useState("");
  const [message, setMessage] = useState("");

  useEffect(() => {
    void (async () => {
      try {
        const [list, active] = await Promise.all([
          repos.scout.listBrands(),
          repos.scout.getActiveBrandId(),
        ]);
        setBrands(list);
        const next = list.find((b) => b.id === brandId)?.id || active || list[0]?.id || "";
        setBrandId(next);
        if (next) setProducts(await repos.scout.listProducts(next));
        else setProducts([]);
      } catch (e) {
        setMessage(e instanceof Error ? e.message : t("brands.loadFail"));
      }
    })();
  }, [repos.scout, tick]); // eslint-disable-line react-hooks/exhaustive-deps

  useEffect(() => {
    if (!brandId) {
      setProducts([]);
      return;
    }
    void repos.scout.listProducts(brandId).then(setProducts);
  }, [brandId, repos.scout]);

  const selected = useMemo(() => brands.find((b) => b.id === brandId) || null, [brands, brandId]);

  const filteredBrands = useMemo(() => {
    const q = brandQuery.trim().toLowerCase();
    if (!q) return brands;
    return brands.filter(
      (b) =>
        b.display_name.toLowerCase().includes(q) ||
        (b.brief || "").toLowerCase().includes(q),
    );
  }, [brands, brandQuery]);

  const pagedBrands = useMemo(
    () => pageSlice(filteredBrands, brandPage, BRAND_PAGE),
    [filteredBrands, brandPage],
  );

  const filteredProducts = useMemo(() => {
    const q = productQuery.trim().toLowerCase();
    if (!q) return products;
    return products.filter(
      (p) =>
        p.label.toLowerCase().includes(q) ||
        p.product_context.toLowerCase().includes(q) ||
        p.match_tags.some((t) => t.toLowerCase().includes(q)) ||
        p.pain_points.some((t) => t.toLowerCase().includes(q)) ||
        p.provider_capability_terms.some((t) => t.toLowerCase().includes(q)) ||
        p.provider_exclude_terms.some((t) => t.toLowerCase().includes(q)),
    );
  }, [products, productQuery]);

  const pagedProducts = useMemo(
    () => pageSlice(filteredProducts, productPage, PRODUCT_PAGE),
    [filteredProducts, productPage],
  );

  useEffect(() => {
    setBrandPage(1);
  }, [brandQuery]);

  useEffect(() => {
    setProductPage(1);
  }, [productQuery, brandId]);

  useEffect(() => {
    if (!selected) {
      setEditName("");
      setEditBrief("");
      setEditAudience("");
      setEditGoals("");
      return;
    }
    setEditName(selected.display_name);
    setEditBrief(selected.brief || "");
    setEditAudience(selected.target_audience || "");
    setEditGoals(selected.goals || "");
  }, [selected]);

  async function selectBrand(id: string) {
    setBrandId(id);
    await repos.scout.setActiveBrandId(id);
    setEditingProductId(null);
    setProductForm(emptyProductForm);
    setShowProductForm(false);
    setImportUrl("");
    setMessage("");
  }

  async function createBrand() {
    const name = newBrandName.trim();
    if (!name) {
      setMessage(t("brands.needName"));
      return;
    }
    setBusy("create");
    setMessage("");
    try {
      const created = await repos.scout.createBrand({ display_name: name });
      setNewBrandName("");
      setShowCreate(false);
      const list = await repos.scout.listBrands();
      setBrands(list);
      setBrandId(created.id);
      setBrandQuery("");
      setBrandPage(1);
      setDetailTab("brand");
      setMessage(t("brands.created", { name: created.display_name }));
      refresh();
    } catch (e) {
      setMessage(e instanceof Error ? e.message : t("brands.createFail"));
    } finally {
      setBusy("");
    }
  }

  async function saveBrand() {
    if (!selected) return;
    setBusy("save");
    setMessage("");
    try {
      const updated = await repos.scout.saveBrand({
        ...selected,
        display_name: editName,
        brief: editBrief,
        target_audience: editAudience,
        goals: editGoals,
      });
      setBrands(await repos.scout.listBrands());
      setBrandId(updated.id);
      setMessage(t("brands.saved"));
      refresh();
    } catch (e) {
      setMessage(e instanceof Error ? e.message : t("brands.saveFail"));
    } finally {
      setBusy("");
    }
  }

  async function deleteBrand() {
    if (!selected) return;
    if (!window.confirm(t("brands.confirmDelete", { name: selected.display_name }))) return;
    setBusy("del");
    try {
      await repos.scout.removeBrand(selected.id);
      const list = await repos.scout.listBrands();
      setBrands(list);
      setBrandId(list[0]?.id || "");
      setMessage(t("brands.deleted"));
      refresh();
    } catch (e) {
      setMessage(e instanceof Error ? e.message : t("brands.deleteFail"));
    } finally {
      setBusy("");
    }
  }

  function startNewProduct() {
    setEditingProductId(null);
    setProductForm(emptyProductForm);
    setImportUrl("");
    setShowProductForm(true);
  }

  function startEditProduct(p: BrandProduct) {
    setEditingProductId(p.id);
    setProductForm({
      label: p.label,
      product_context: p.product_context,
      pain_points: p.pain_points.join("\n"),
      match_tags: p.match_tags.join(", "),
      provider_capability_terms: p.provider_capability_terms.join(", "),
      provider_exclude_terms: p.provider_exclude_terms.join(", "),
      placement_url: p.placement_url || "",
    });
    setImportUrl(p.placement_url || "");
    setShowProductForm(true);
  }

  function cancelEditProduct() {
    setEditingProductId(null);
    setProductForm(emptyProductForm);
    setImportUrl("");
    setShowProductForm(false);
  }

  async function importFromUrl() {
    if (!brandId) return;
    setBusy("import");
    setMessage("");
    try {
      const draft = await repos.scout.importProductFromUrl(importUrl || productForm.placement_url);
      setProductForm({
        label: draft.label,
        product_context: draft.product_context,
        pain_points: draft.pain_points.join("\n"),
        match_tags: draft.match_tags.join(", "),
        provider_capability_terms: "",
        provider_exclude_terms: "",
        placement_url: draft.placement_url,
      });
      setImportUrl(draft.placement_url);
      setMessage(draft.source_note);
    } catch (e) {
      setMessage(e instanceof Error ? e.message : t("brands.fetchFail"));
    } finally {
      setBusy("");
    }
  }

  async function saveProduct() {
    if (!brandId) return;
    const label = productForm.label.trim();
    const ctx = productForm.product_context.trim();
    if (!label || !ctx) {
      setMessage(t("brands.needLabelContext"));
      return;
    }
    setBusy("product");
    setMessage("");
    try {
      const pain_points = productForm.pain_points
        .split(/[\n,，]+/)
        .map((s) => s.trim())
        .filter(Boolean);
      const provider_capability_terms = productForm.provider_capability_terms
        .split(/[\n,，、]+/)
        .map((s) => s.trim())
        .filter(Boolean);
      const provider_exclude_terms = productForm.provider_exclude_terms
        .split(/[\n,，、]+/)
        .map((s) => s.trim())
        .filter(Boolean);
      const match_tags = productForm.match_tags
        .split(/[,\s，、]+/)
        .map((s) => s.trim())
        .filter(Boolean);
      const existing = editingProductId
        ? products.find((p) => p.id === editingProductId)
        : null;
      await repos.scout.saveProduct({
        id: editingProductId || newId("prod"),
        brand_id: brandId,
        label,
        product_context: ctx,
        pain_points,
        match_tags,
        provider_capability_terms,
        provider_exclude_terms,
        placement_url: productForm.placement_url.trim() || undefined,
        created_at: existing?.created_at || nowUnixNano(),
        updated_at: nowUnixNano(),
      });
      setProducts(await repos.scout.listProducts(brandId));
      cancelEditProduct();
      setMessage(editingProductId ? t("brands.productUpdated") : t("brands.productAdded"));
      refresh();
    } catch (e) {
      setMessage(e instanceof Error ? e.message : t("brands.saveFail"));
    } finally {
      setBusy("");
    }
  }

  async function removeProduct(id: string) {
    setBusy("delProd");
    try {
      const affected = await repos.radar.listWatches(1, 100, undefined, undefined, undefined, id);
      const impact = affected.list.filter((w) => w.status === "active" || w.status === "paused").length;
      const confirmText = `${t("brands.confirmDeleteProduct")}${impact ? `\n\n${t("brands.deleteImpact", { n: impact })}` : ""}`;
      if (!window.confirm(confirmText)) {
        setBusy("");
        return;
      }
      await repos.scout.removeProduct(id);
      setProducts(await repos.scout.listProducts(brandId));
      if (editingProductId === id) cancelEditProduct();
      setMessage(t("brands.deleted"));
      refresh();
    } catch (e) {
      setMessage(e instanceof Error ? e.message : t("brands.deleteFail"));
    } finally {
      setBusy("");
    }
  }

  return (
    <>
      <PageHeader title={t("brands.title")} />

      {message ? (
        <p className="hb-banner-ok" role="status">
          {message}
        </p>
      ) : null}

      <div className="hb-brands">
        {/* 選牌區：手機橫向 chip，桌面左側列表 */}
        <aside className="hb-brands__rail" aria-label={t("brands.railAria")}>
          <div className="hb-brands__rail-head">
            <div className="hb-brands__rail-title">
              <span className="hb-brands__rail-label">{t("brands.railLabel")}</span>
              {brands.length > 0 ? (
                <span className="hb-brands__count">{brands.length}</span>
              ) : null}
            </div>
            <Button
              type="button"
              variant={showCreate ? "ghost" : "secondary"}
              onClick={() => {
                setShowCreate((v) => !v);
                setMessage("");
              }}
            >
              {showCreate ? t("common.cancel") : t("brands.add")}
            </Button>
          </div>

          {showCreate ? (
            <div className="hb-brands__create">
              <Input
                label={t("brands.brandName")}
                value={newBrandName}
                onChange={(e) => setNewBrandName(e.target.value)}
                placeholder={t("brands.brandNamePh")}
                onKeyDown={(e) => {
                  if (e.key === "Enter") void createBrand();
                }}
              />
              <Button type="button" onClick={() => void createBrand()} disabled={busy === "create"}>
                {busy === "create" ? t("brands.creating") : t("brands.createBrand")}
              </Button>
            </div>
          ) : null}

          {brands.length > 0 ? (
            <div className="hb-brands__search">
              <Input
                label=""
                aria-label={t("brands.searchAria")}
                value={brandQuery}
                onChange={(e) => setBrandQuery(e.target.value)}
                placeholder={t("brands.searchPh")}
              />
            </div>
          ) : null}

          {brands.length === 0 ? (
            <p className="hb-brands__empty-hint">{t("brands.empty")}</p>
          ) : filteredBrands.length === 0 ? (
            <p className="hb-brands__empty-hint">{t("brands.noMatch")}</p>
          ) : (
            <>
              <div className="hb-brands__chips" role="listbox" aria-label={t("brands.selectAria")}>
                {pagedBrands.map((b) => (
                  <button
                    key={b.id}
                    type="button"
                    role="option"
                    aria-selected={b.id === brandId}
                    className={`hb-brands__chip${b.id === brandId ? " is-active" : ""}`}
                    onClick={() => void selectBrand(b.id)}
                  >
                    <span className="hb-brands__chip-mark" aria-hidden>
                      {(b.display_name.trim()[0] || "?").toUpperCase()}
                    </span>
                    <span className="hb-brands__chip-name">{b.display_name}</span>
                  </button>
                ))}
              </div>
              <Pager
                className="hb-pager--compact"
                total={filteredBrands.length}
                page={brandPage}
                pageSize={BRAND_PAGE}
                onPageChange={setBrandPage}
              />
            </>
          )}
        </aside>

        {/* 焦點編輯 */}
        <section className="hb-brands__panel">
          {!selected ? (
            <EmptyState title={t("brands.pickOne")} />
          ) : (
            <>
              <header className="hb-brands__panel-head">
                <div className="hb-brands__panel-identity">
                  <span className="hb-brands__avatar" aria-hidden>
                    {(selected.display_name.trim()[0] || "?").toUpperCase()}
                  </span>
                  <div className="hb-brands__panel-titles">
                    <h2>{selected.display_name}</h2>
                    <p className="text-muted">{t("brands.inUseHint")}</p>
                    {selected.learning_summary ? (
                      <p className="text-muted">{selected.learning_summary}</p>
                    ) : null}
                  </div>
                </div>
                <Badge tone="brand">{t("brands.inUse")}</Badge>
              </header>

              <div className="hb-tabs hb-tabs--segment" role="tablist">
                <button
                  type="button"
                  role="tab"
                  aria-selected={detailTab === "brand"}
                  className={`hb-tab ${detailTab === "brand" ? "is-active" : ""}`}
                  onClick={() => setDetailTab("brand")}
                >
                  {t("brands.tabInfo")}
                </button>
                <button
                  type="button"
                  role="tab"
                  aria-selected={detailTab === "products"}
                  className={`hb-tab ${detailTab === "products" ? "is-active" : ""}`}
                  onClick={() => {
                    setDetailTab("products");
                    setShowProductForm(false);
                    setEditingProductId(null);
                  }}
                >
                  {products.length ? t("brands.tabProductsN", { n: products.length }) : t("brands.tabProducts")}
                </button>
              </div>

              {detailTab === "brand" ? (
                <div className="hb-brands__form">
                  <Input label={t("brands.displayName")} value={editName} onChange={(e) => setEditName(e.target.value)} />
                  <Textarea
                    label={t("brands.brief")}
                    value={editBrief}
                    onChange={(e) => setEditBrief(e.target.value)}
                    rows={3}
                    placeholder={t("brands.briefPh")}
                  />
                  <Textarea
                    label={t("brands.audience")}
                    value={editAudience}
                    onChange={(e) => setEditAudience(e.target.value)}
                    rows={3}
                    placeholder={t("brands.audiencePh")}
                  />
                  <Textarea
                    label={t("brands.goals")}
                    value={editGoals}
                    onChange={(e) => setEditGoals(e.target.value)}
                    rows={3}
                    placeholder={t("brands.goalsPh")}
                  />
                  <div className="hb-brands__actions">
                    <Button type="button" onClick={() => void saveBrand()} disabled={busy === "save"}>
                      {busy === "save" ? t("brands.saving") : t("common.save")}
                    </Button>
                    <Button
                      type="button"
                      variant="ghost"
                      onClick={() => void deleteBrand()}
                      disabled={busy === "del"}
                      className="hb-brands__danger-ghost"
                    >
                      {t("brands.deleteBrand")}
                    </Button>
                  </div>
                </div>
              ) : null}

              {detailTab === "products" ? (
                <div className="hb-brands__products">
                  {!showProductForm ? (
                    <>
                      <div className="hb-brands__products-bar">
                        {products.length > 0 ? (
                          <div className="hb-brands__products-search">
                            <Input
                              label=""
                              aria-label={t("brands.searchProductAria")}
                              value={productQuery}
                              onChange={(e) => setProductQuery(e.target.value)}
                              placeholder={t("brands.searchProductPh")}
                            />
                          </div>
                        ) : (
                          <div />
                        )}
                        <Button type="button" onClick={startNewProduct}>
                          {t("brands.addProduct")}
                        </Button>
                      </div>

                      {products.length === 0 ? (
                        <EmptyState title={t("brands.noProducts")} />
                      ) : filteredProducts.length === 0 ? (
                        <EmptyState title={t("brands.noMatch")} />
                      ) : (
                        <>
                          <ul className="hb-brands__product-list">
                            {pagedProducts.map((p) => (
                              <li key={p.id} className="hb-brands__product-card">
                                <div className="hb-brands__product-top">
                                  <strong className="hb-brands__product-name">{p.label}</strong>
                                  {p.placement_url ? <Badge tone="brand">{t("brands.hasLink")}</Badge> : null}
                                </div>
                                {p.pain_points.length ? (
                                  <p className="hb-brands__product-meta">
                                    <span className="text-muted">{t("brands.painLabel")}</span>
                                    {p.pain_points.join(" · ")}
                                  </p>
                                ) : null}
                                <p className="hb-brands__product-body">{p.product_context}</p>
                                {p.match_tags.length ? (
                                  <div className="hb-inline-badges">
                                    {p.match_tags.map((t) => (
                                      <Badge key={t} tone="neutral">
                                        {t}
                                      </Badge>
                                    ))}
                                  </div>
                                ) : null}
                                <div className="hb-brands__product-actions">
                                  <Button
                                    type="button"
                                    variant="secondary"
                                    onClick={() => startEditProduct(p)}
                                  >
                                    {t("common.edit")}
                                  </Button>
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    onClick={() => void removeProduct(p.id)}
                                    disabled={busy === "delProd"}
                                  >
                                    {t("common.delete")}
                                  </Button>
                                </div>
                              </li>
                            ))}
                          </ul>
                          <Pager
                            total={filteredProducts.length}
                            page={productPage}
                            pageSize={PRODUCT_PAGE}
                            onPageChange={setProductPage}
                          />
                        </>
                      )}
                    </>
                  ) : (
                    <div className="hb-brands__product-form">
                      <div className="hb-brands__product-form-head">
                        <h3>{editingProductId ? t("brands.editProduct") : t("brands.newProduct")}</h3>
                        <Button type="button" variant="ghost" onClick={cancelEditProduct}>
                          {t("common.cancel")}
                        </Button>
                      </div>
                      <div className="hb-brands__import">
                        <Input
                          label={t("brands.importFromUrl")}
                          value={importUrl}
                          onChange={(e) => setImportUrl(e.target.value)}
                          placeholder="https://…"
                          onKeyDown={(e) => {
                            if (e.key === "Enter") void importFromUrl();
                          }}
                        />
                        <Button
                          type="button"
                          variant="secondary"
                          onClick={() => void importFromUrl()}
                          disabled={busy === "import"}
                        >
                          {busy === "import" ? t("brands.fetching") : t("brands.fetch")}
                        </Button>
                      </div>
                      <Input
                        label={t("brands.displayName")}
                        value={productForm.label}
                        onChange={(e) => setProductForm((f) => ({ ...f, label: e.target.value }))}
                      />
                      <Textarea
                        label={t("brands.providerCapabilities")}
                        value={productForm.provider_capability_terms}
                        onChange={(e) =>
                          setProductForm((f) => ({ ...f, provider_capability_terms: e.target.value }))
                        }
                        placeholder={t("brands.providerCapabilitiesPh")}
                        rows={2}
                      />
                      <Input
                        label={t("brands.providerExcludes")}
                        value={productForm.provider_exclude_terms}
                        onChange={(e) =>
                          setProductForm((f) => ({ ...f, provider_exclude_terms: e.target.value }))
                        }
                        placeholder={t("brands.providerExcludesPh")}
                      />
                      <Textarea
                        label={t("brands.pains")}
                        value={productForm.pain_points}
                        onChange={(e) =>
                          setProductForm((f) => ({ ...f, pain_points: e.target.value }))
                        }
                        placeholder={t("brands.painsPh")}
                        rows={3}
                      />
                      <Input
                        label={t("brands.tags")}
                        value={productForm.match_tags}
                        onChange={(e) =>
                          setProductForm((f) => ({ ...f, match_tags: e.target.value }))
                        }
                        placeholder={t("brands.tagsPh")}
                      />
                      <Textarea
                        label={t("brands.intro")}
                        value={productForm.product_context}
                        onChange={(e) =>
                          setProductForm((f) => ({ ...f, product_context: e.target.value }))
                        }
                        rows={4}
                      />
                      <Input
                        label={t("brands.link")}
                        value={productForm.placement_url}
                        onChange={(e) =>
                          setProductForm((f) => ({ ...f, placement_url: e.target.value }))
                        }
                        placeholder="https://…"
                      />
                      <div className="hb-brands__actions">
                        <Button
                          type="button"
                          onClick={() => void saveProduct()}
                          disabled={busy === "product"}
                        >
                          {busy === "product"
                            ? t("brands.saving")
                            : editingProductId
                              ? t("brands.update")
                              : t("brands.createItem")}
                        </Button>
                        <Button type="button" variant="ghost" onClick={cancelEditProduct}>
                          {t("common.cancel")}
                        </Button>
                      </div>
                    </div>
                  )}
                </div>
              ) : null}
            </>
          )}
        </section>
      </div>
    </>
  );
}
