/* global React, Icon, Button, Field, Dialog, useToast, ADJ_BATCH_LIBRARY, ADJ_BATCHES, UserChip */
// Dialog shown when the user clicks 「新增調整單」
// Follows the same two-mode architecture as new-product/batch-picker.jsx

const { useState, useMemo } = React;

const AdjPicker = ({ open, onClose, adjBatches, currentUser, onConfirm }) => {
  const [mode, setMode] = useState("existing"); // "existing" | "new"
  const [picked, setPicked] = useState("");
  const [newName, setNewName] = useState("");
  const [search, setSearch] = useState("");

  const myBatchNames = new Set(
    adjBatches.filter(b => b.applicant === currentUser).map(b => b.batchName)
  );

  const visibleBatches = useMemo(() => {
    return ADJ_BATCH_LIBRARY.filter(b => !search || b.includes(search));
  }, [search]);

  if (!open) return null;

  const conflict = mode === "existing" && picked && myBatchNames.has(picked);
  const newNameInvalid = mode === "new" && newName && !/^[A-Za-z0-9_一-龥]{4,40}$/.test(newName);
  const dupeNewName = mode === "new" && newName && ADJ_BATCH_LIBRARY.includes(newName);

  const canSubmit = mode === "existing"
    ? !!picked && !conflict
    : !!newName && !newNameInvalid && !dupeNewName;

  const submit = () => {
    if (!canSubmit) return;
    const batchName = mode === "existing" ? picked : newName;
    if (mode === "new" && !ADJ_BATCH_LIBRARY.includes(batchName)) ADJ_BATCH_LIBRARY.push(batchName);
    onConfirm(batchName);
    setPicked(""); setNewName(""); setSearch(""); setMode("existing");
  };

  return (
    <Dialog open={open} title="新增調整單" onClose={onClose}
      footer={<>
        <Button variant="text" onClick={onClose}>取消</Button>
        <Button variant="primary" onClick={submit} disabled={!canSubmit}>
          {mode === "new" ? "建立新批次並進入" : "進入該批次調整單"}
        </Button>
      </>}>
      <div className="batch-picker">
        <div className="form-row" style={{ marginBottom: 12, gridTemplateColumns: "90px 1fr", alignItems: "center" }}>
          <div className="lab" style={{ paddingTop: 0 }}>申請人</div>
          <div>
            <UserChip name={currentUser} />
            <span style={{ color: "var(--fg-3)", fontSize: 12, marginLeft: 8 }}>
              調整單會掛在你的名下，由你編輯
            </span>
          </div>
        </div>

        <div className="seg">
          <button className={"seg__btn" + (mode === "existing" ? " on" : "")} onClick={() => setMode("existing")}>
            <Icon name="list" size={13} /> 選現有批次
          </button>
          <button className={"seg__btn" + (mode === "new" ? " on" : "")} onClick={() => setMode("new")}>
            <Icon name="plus" size={13} /> 新建批次
          </button>
        </div>

        {mode === "existing" && (
          <>
            <Field leading="search" placeholder="搜尋批次名稱…" value={search} onChange={e => setSearch(e.target.value)}
              style={{ marginBottom: 8 }} />
            <div className="batch-list">
              {visibleBatches.map(b => {
                const owned = myBatchNames.has(b);
                return (
                  <div key={b}
                    className={"batch-list__row" + (picked === b ? " on" : "") + (owned ? " disabled" : "")}
                    onClick={() => !owned && setPicked(b)}>
                    <div className="batch-list__radio">
                      {picked === b ? <span className="batch-list__dot" /> : null}
                    </div>
                    <div>
                      <div className="batch-list__name">{b}</div>
                      {owned && (
                        <div className="batch-list__hint batch-list__hint--warn">
                          你已在此批次有一張調整單，請改在原單繼續編輯
                        </div>
                      )}
                    </div>
                    <Icon name="chevRight" size={12} />
                  </div>
                );
              })}
              {visibleBatches.length === 0 && (
                <div className="batch-list__empty">沒有符合條件的批次。試試新建一個？</div>
              )}
            </div>
            {conflict && (
              <div className="help err" style={{ marginTop: 8 }}>
                你已在 <b>{picked}</b> 有一張調整單，請至列表編輯原單。
              </div>
            )}
          </>
        )}

        {mode === "new" && (
          <div className="form-row" style={{ gridTemplateColumns: "90px 1fr" }}>
            <div className="lab req">批次名稱</div>
            <div>
              <Field
                placeholder="例：Phase_111週次05_30廠商調整"
                value={newName}
                onChange={e => setNewName(e.target.value)}
                error={newNameInvalid || dupeNewName}
              />
              {newNameInvalid && <div className="help err">4–40 碼，僅可包含中英文／數字／底線</div>}
              {dupeNewName && <div className="help err">此批次名稱已存在</div>}
              {!newNameInvalid && !dupeNewName && (
                <div className="help">命名建議：Phase_[期數]_[週次]廠商調整，建立後其他採購可選擇加入</div>
              )}
            </div>
          </div>
        )}
      </div>
    </Dialog>
  );
};

Object.assign(window, { AdjPicker });
