/* global React, PageHead, Button, Icon, Tag, Field, Select, Textarea, NumInput, Check,
   PortalSelect, Dialog, SlideDrawer, Pager, ModeToggle, ChipFilter, BulkBar, MetaCard, EmptyState,
   InfoNote, SysCheckBanner, ApprovalStatusBanner, ChangePill, UserChip, FormField,
   FormFieldVal, RadioCard, RadioGroup, SegControl, StatusSwitch, FormSectionDivider,
   FilterBar, Crumb, InfoTip, useSortableTable, useToast */

const { useState } = React;

const DS_NAV = [
  { id: "ds-type", label: "Typography" },
  { id: "ds-color", label: "Color" },
  { id: "ds-button", label: "Button" },
  { id: "ds-icon", label: "Icon" },
  { id: "ds-tag", label: "Tag" },
  { id: "ds-form", label: "Form" },
  { id: "ds-select", label: "Selection" },
  { id: "ds-feedback", label: "Feedback" },
  { id: "ds-layout", label: "Layout" },
  { id: "ds-overlay", label: "Overlay" },
  { id: "ds-drawer", label: "Drawer" },
];

const VENDOR_GROUPED = [
  { group: "常溫廠商", options: [
    { value: "v1", label: "統一企業" },
    { value: "v2", label: "味全食品" },
    { value: "v3", label: "義美食品" },
  ] },
  { group: "冷藏廠商", options: [
    { value: "v4", label: "光泉牧場" },
    { value: "v5", label: "福樂食品" },
  ] },
];

const ICON_SAMPLES = [
  "search", "plus", "check", "close", "edit", "trash", "download", "upload",
  "filter", "eye", "info", "warn", "alertCircle", "chevDown", "chevRight",
  "send", "lock", "tag", "menu", "sliders", "box", "user", "cog", "shield",
];

const COLOR_SWATCHES = [
  { token: "--brand-primary", label: "Primary" },
  { token: "--brand-primary-text", label: "Primary text" },
  { token: "--brand-eats-green", label: "Eats green" },
  { token: "--fg-1", label: "fg-1" },
  { token: "--fg-2", label: "fg-2" },
  { token: "--fg-3", label: "fg-3" },
  { token: "--bg-page", label: "bg-page" },
  { token: "--bg-surface", label: "bg-surface" },
  { token: "--success", label: "success" },
  { token: "--warning", label: "warning" },
  { token: "--danger", label: "danger" },
  { token: "--info", label: "info" },
];

const TYPE_SAMPLES = [
  { cls: "ds-type--32", token: "--fs-32", weight: "--fw-bold", label: "32 / Bold" },
  { cls: "ds-type--24", token: "--fs-24", weight: "--fw-semibold", label: "24 / Semibold" },
  { cls: "ds-type--20", token: "--fs-20", weight: "--fw-semibold", label: "20 / Semibold" },
  { cls: "ds-type--16", token: "--fs-16", weight: "--fw-medium", label: "16 / Medium" },
  { cls: "ds-type--14", token: "--fs-14", weight: "--fw-regular", label: "14 / Regular" },
  { cls: "ds-type--13", token: "--fs-13", weight: "--fw-regular", label: "13 / Regular" },
  { cls: "ds-type--12", token: "--fs-12", weight: "--fw-regular", label: "12 / Regular" },
];

const TAG_SAMPLES = [
  "draft", "review", "approved", "rejected", "hold",
  "active", "expired", "coUnderReview", "coNoReview", "condField",
];

const DSSection = ({ id, title, desc, bare, children }) => (
  <section id={id} className="ds-section">
    <h2 className="ds-section__title">{title}</h2>
    {desc && <p className="ds-section__desc">{desc}</p>}
    {bare ? children : <div className="ds-panel">{children}</div>}
  </section>
);

const DSRow = ({ label, children, className = "" }) => (
  <div className={"ds-row " + className}>
    {label && <div className="ds-row__label">{label}</div>}
    {children}
  </div>
);

const MainIntroDesignSystem = ({ onBack }) => {
  const toast = useToast();
  const [activeNav, setActiveNav] = useState("ds-type");
  const [dialogOpen, setDialogOpen] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [mode, setMode] = useState("compact");
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [chipVal, setChipVal] = useState([]);
  const [portalVal, setPortalVal] = useState("");
  const [portalMulti, setPortalMulti] = useState([]);
  const [portalGroup, setPortalGroup] = useState("");
  const [radioCard, setRadioCard] = useState("a");
  const [radioGrp, setRadioGrp] = useState("x");
  const [segVal, setSegVal] = useState("all");
  const [statusOn, setStatusOn] = useState(true);

  const scrollTo = (id) => {
    setActiveNav(id);
    document.getElementById(id)?.scrollIntoView({ behavior: "smooth", block: "start" });
  };

  return (
    <div className="main-intro__inner">
      <PageHead
        crumbs={[
          { label: "原型入口", onClick: onBack },
          { label: "Design System", current: true },
        ]}
        title="Design System"
        subtitle="共用元件與 design token 展示。來源：styles/tokens.css、styles/ui-kit.css、scripts/primitives.jsx"
        actions={<Button variant="default" onClick={onBack}>返回入口</Button>}
      />

      <div className="ds-layout">
        <nav className="ds-nav" aria-label="Design System 章節">
          {DS_NAV.map(item => (
            <button
              key={item.id}
              type="button"
              className={"ds-nav__link" + (activeNav === item.id ? " is-active" : "")}
              onClick={() => scrollTo(item.id)}
            >
              {item.label}
            </button>
          ))}
        </nav>

        <div className="ds-main">
          <DSSection id="ds-type" title="Typography" desc="字型三件套：Inter + Noto Sans TC + JetBrains Mono。禁止 font shorthand。">
            {TYPE_SAMPLES.map(s => (
              <DSRow key={s.token} label={s.label}>
                <p
                  className={"ds-type-sample " + s.cls}
                  style={{ fontSize: "var(" + s.token + ")", fontWeight: "var(" + s.weight + ")" }}
                >
                  商品主檔調整單 AB-2024-001 · NT$1,280
                </p>
              </DSRow>
            ))}
            <DSRow label="Mono（SKU / 價格 / 時間）">
              <span style={{ fontFamily: "var(--font-mono)", fontSize: "var(--fs-13)", color: "var(--fg-1)" }}>
                TW019000047156-00 · 2026-06-24 14:30
              </span>
            </DSRow>
          </DSSection>

          <DSSection id="ds-color" title="Color" desc="顏色一律使用 tokens.css 變數，禁止 hardcode RGB。">
            <div className="ds-swatch-grid">
              {COLOR_SWATCHES.map(s => (
                <div key={s.token} className="ds-swatch">
                  <div className="ds-swatch__chip" style={{ background: "var(" + s.token + ")" }} />
                  <div className="ds-swatch__meta">{s.label}<br />{s.token}</div>
                </div>
              ))}
            </div>
          </DSSection>

          <DSSection id="ds-button" title="Button" desc="圓角 4px。CTA 綠色用量 ≤ 5%，primary 只用於主要操作。">
            <DSRow label="Variants">
              <Button variant="default">取消</Button>
              <Button variant="secondary">儲存草稿</Button>
              <Button variant="primary">確認送出</Button>
              <Button variant="danger">刪除</Button>
              <Button variant="text">純文字</Button>
            </DSRow>
            <DSRow label="With icon">
              <Button variant="primary" icon="send">送出</Button>
              <Button variant="default" icon="download">匯出</Button>
              <Button variant="default" icon="plus">新增 SKU</Button>
            </DSRow>
            <DSRow label="Size">
              <Button variant="default" size="sm">Small</Button>
              <Button variant="default">Default</Button>
              <Button variant="default" size="lg">Large</Button>
              <Button variant="default" icon="edit" iconOnly />
            </DSRow>
            <DSRow label="Disabled">
              <Button variant="primary" disabled>Primary</Button>
              <Button variant="default" disabled>Default</Button>
            </DSRow>
          </DSSection>

          <DSSection id="ds-icon" title="Icon" desc="全站 SVG 圖示庫。size 預設 16，顏色繼承父層 color。">
            <div className="ds-icon-grid">
              {ICON_SAMPLES.map(name => (
                <div key={name} className="ds-icon-cell">
                  <Icon name={name} size={18} />
                  <span>{name}</span>
                </div>
              ))}
            </div>
          </DSSection>

          <DSSection id="ds-tag" title="Tag" desc="狀態標籤。文案來源 STATUS map，禁止各模組自行寫字串。">
            <DSRow label="審核 / 狀態">
              {TAG_SAMPLES.map(st => <Tag key={st} status={st} />)}
            </DSRow>
            <DSRow label="自訂文案">
              <Tag variant="draft">自訂草稿</Tag>
              <Tag variant="teal">Teal</Tag>
            </DSRow>
          </DSSection>

          <DSSection id="ds-form" title="Form" desc="表單欄位與 FormField 包裝。">
            <div className="ds-demo-wide" style={{ display: "flex", flexDirection: "column", gap: 14 }}>
              <FormField label="品名" required>
                <Field placeholder="輸入品名" defaultValue="統一肉燥風味即食包" />
              </FormField>
              <FormField label="搜尋" hint="leading icon 範例">
                <Field leading="search" placeholder="搜尋品號、品名…" />
              </FormField>
              <FormField label="錯誤狀態" error="格式應為 8 位數字">
                <Field error defaultValue="ABC" />
              </FormField>
              <FormField label="稅別" required>
                <Select defaultValue="5">
                  <option value="5">5%</option>
                  <option value="0">0%</option>
                </Select>
              </FormField>
              <FormField label="進價（未稅）" required>
                <NumInput value="196.43" unit="NT$" onChange={() => {}} />
              </FormField>
              <FormField label="商品資訊備註">
                <Textarea placeholder="多行輸入…" defaultValue="常溫保存，效期 365 天。" />
              </FormField>
              <FormField label="退回原因" error="請填寫退回原因">
                <Textarea variant="reject" placeholder="說明退回原因…" />
              </FormField>
              <FormField label="建立日期" locked>
                <FormFieldVal>2026-06-24</FormFieldVal>
              </FormField>
              <FormField label="品號" locked>
                <FormFieldVal mono>TW019000047156-00</FormFieldVal>
              </FormField>
              <FormSectionDivider badge="A" label="商品識別" first />
            </div>
          </DSSection>

          <DSSection id="ds-select" title="Selection" desc="Checkbox、Radio、Segment、Switch、PortalSelect。">
            <DSRow label="Check">
              <Check checked={false} onChange={() => {}} />
              <Check checked onChange={() => {}} />
              <Check checked indeterminate onChange={() => {}} />
              <Check checked readOnly onChange={() => {}} />
              <Check disabled onChange={() => {}} />
            </DSRow>
            <DSRow label="RadioCard">
              <RadioCard
                name="ds-radio-card"
                value={radioCard}
                onChange={setRadioCard}
                options={[
                  { id: "a", label: "選項 A", hint: "說明文字一行" },
                  { id: "b", label: "選項 B", hint: "另一個選項" },
                ]}
              />
            </DSRow>
            <DSRow label="RadioGroup">
              <RadioGroup
                value={radioGrp}
                onChange={setRadioGrp}
                options={[["是", "x"], ["否", "y"]]}
              />
            </DSRow>
            <DSRow label="SegControl">
              <SegControl
                value={segVal}
                onChange={setSegVal}
                options={[
                  { id: "all", label: "全部" },
                  { id: "mine", label: "我的", badge: "3" },
                ]}
              />
            </DSRow>
            <DSRow label="StatusSwitch">
              <StatusSwitch on={statusOn} onClick={() => setStatusOn(v => !v)} />
            </DSRow>
            <DSRow label="PortalSelect — 單選" className="ds-demo-narrow">
              <PortalSelect
                value={portalVal}
                onChange={setPortalVal}
                placeholder="選擇廠商"
                options={[
                  { value: "v1", label: "統一企業" },
                  { value: "v2", label: "味全食品" },
                  { value: "v3", label: "義美食品" },
                ]}
              />
            </DSRow>
            <DSRow label="PortalSelect — 多選" className="ds-demo-narrow">
              <PortalSelect
                multi
                value={portalMulti}
                onChange={setPortalMulti}
                placeholder="選擇分類（可複選）"
                options={[
                  { value: "c1", label: "飲料" },
                  { value: "c2", label: "乳製品" },
                  { value: "c3", label: "零食" },
                  { value: "c4", label: "冷凍食品" },
                ]}
              />
            </DSRow>
            <DSRow label="PortalSelect — 分組" className="ds-demo-narrow">
              <PortalSelect
                value={portalGroup}
                onChange={setPortalGroup}
                placeholder="選擇廠商（分組）"
                options={VENDOR_GROUPED}
              />
            </DSRow>
          </DSSection>

          <DSSection id="ds-feedback" title="Feedback" desc="提示、Banner、空狀態、Toast。">
            <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
              <InfoNote>商品主圖由 Samantha 後續上傳，建立單送出後不可修改品號。</InfoNote>
              <InfoNote variant="warning">毛利率低於 20%，送審後需主管審核。</InfoNote>
              <SysCheckBanner allPass errorCount={0} />
              <SysCheckBanner allPass={false} errorCount={2} />
              <ApprovalStatusBanner variant="rejected" msg="主管已退回：進價調幅超過 15%，請修正後重新送出。" />
              <div style={{ display: "flex", gap: 12, alignItems: "center" }}>
                <ChangePill count={3} />
                <ChangePill count={1} hasErr />
                <UserChip name="Neilson" />
              </div>
              <Button variant="default" onClick={() => toast.push({ msg: "已儲存草稿", kind: "success" })}>
                觸發 Toast
              </Button>
              <EmptyState icon="inbox" title="尚無資料" desc="調整篩選條件或新增第一筆。">
                <Button variant="primary" icon="plus">新增</Button>
              </EmptyState>
            </div>
          </DSSection>

          <DSSection id="ds-layout" title="Layout" desc="PageHead、Crumb、FilterBar、ModeToggle、Pager、MetaCard、BulkBar。">
            <DSRow label="Crumb">
              <Crumb items={[
                { label: "商品調整", disabled: true },
                { label: "轉廠商調整", onClick: () => {} },
                { label: "AV-2024-001", current: true },
              ]} />
            </DSRow>
            <DSRow label="FilterBar + ChipFilter">
              <FilterBar filters={[
                { type: "search", placeholder: "搜尋…", value: "", onChange: () => {} },
              ]} />
              <ChipFilter
                label="狀態"
                multi
                value={chipVal}
                onChange={setChipVal}
                options={["草稿", "待審核", "審核通過"]}
              />
            </DSRow>
            <DSRow label="ModeToggle">
              <ModeToggle mode={mode} onChange={setMode} />
            </DSRow>
            <DSRow label="BulkBar">
              <BulkBar label="已選 2 筆">
                <Button variant="default" size="sm">批次刪除</Button>
              </BulkBar>
            </DSRow>
            <DSRow label="Pager">
              <Pager
                total={128}
                page={page}
                pageSize={pageSize}
                onPageChange={setPage}
                onSizeChange={ps => { setPageSize(ps); setPage(1); }}
              />
            </DSRow>
            <DSRow label="MetaCard">
              <div className="ds-demo-wide">
                <MetaCard
                  summary="批次 AV-2024-001 · Neilson · 共 12 筆 · 待審核"
                  sectionTitle="批次資訊"
                >
                  <div className="meta-card__row"><dt>申請人</dt><dd>Neilson</dd></div>
                  <div className="meta-card__row"><dt>狀態</dt><dd><Tag status="adjSubmitted" /></dd></div>
                </MetaCard>
              </div>
            </DSRow>
          </DSSection>

          <DSSection id="ds-overlay" title="Overlay" desc="Dialog 尺寸 content-driven，圓角 6px。">
            <Button variant="primary" onClick={() => setDialogOpen(true)}>開啟 Dialog</Button>
            <Dialog
              open={dialogOpen}
              title="確認刪除"
              onClose={() => setDialogOpen(false)}
              footer={
                <>
                  <Button variant="default" onClick={() => setDialogOpen(false)}>取消</Button>
                  <Button variant="danger" onClick={() => { setDialogOpen(false); toast.push({ msg: "已刪除", kind: "success" }); }}>確認刪除</Button>
                </>
              }
            >
              <p style={{ margin: 0, fontSize: "var(--fs-13)", color: "var(--fg-2)", lineHeight: 1.6 }}>
                刪除後無法復原。確定要刪除這筆草稿嗎？
              </p>
            </Dialog>
          </DSSection>

          <DSSection id="ds-drawer" title="Drawer" desc="側邊抽屜（SlideDrawer）。右側滑入，head / body / foot 三段；body 自動捲動，foot 結構性置底。關閉時若有未儲存變更會跳放棄確認。">
            <DSRow label="SlideDrawer">
              <Button variant="primary" icon="edit" onClick={() => setDrawerOpen(true)}>開啟側邊抽屜</Button>
            </DSRow>
            {drawerOpen && (
              <SlideDrawer
                title="編輯商品 · TW019000047156-00"
                meta={<Tag status="review" />}
                onClose={() => setDrawerOpen(false)}
                foot={(close) => (
                  <>
                    <Button variant="default" onClick={close}>取消</Button>
                    <Button variant="primary" icon="check" onClick={() => { setDrawerOpen(false); toast.push({ msg: "已儲存", kind: "success" }); }}>儲存</Button>
                  </>
                )}
              >
                <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
                  <FormSectionDivider badge="A" label="商品識別" first />
                  <FormField label="品號" locked>
                    <FormFieldVal mono>TW019000047156-00</FormFieldVal>
                  </FormField>
                  <FormField label="品名" required>
                    <Field defaultValue="統一肉燥風味即食包" />
                  </FormField>
                  <FormSectionDivider badge="D" label="進價與定價" />
                  <FormField label="進價（未稅）" required>
                    <NumInput value="196.43" unit="NT$" onChange={() => {}} />
                  </FormField>
                  <FormField label="廠商" required>
                    <PortalSelect value="" onChange={() => {}} placeholder="選擇廠商" options={VENDOR_GROUPED} />
                  </FormField>
                  <FormField label="商品資訊備註">
                    <Textarea placeholder="多行輸入…" />
                  </FormField>
                </div>
              </SlideDrawer>
            )}
          </DSSection>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { MainIntroDesignSystem });
