/* global React, Icon, Button, Field, Dialog, useToast, BATCH_LIBRARY, UserChip */
// Dialog shown when the user clicks 「新增建立單」
// Step 1: pick an existing batch OR type a new batch name
// (Always tied to the current user, since a form is unique by applicant × batch)

const { useState, useMemo } = React;

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

  const myFormsByBatch = new Set(
    existingForms.filter(f => f.applicant === currentUser).map(f => f.batch)
  );

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

  if (!open) return null;

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

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

  const submit = () => {
    if (!canSubmit) return;
    const batch = mode === "existing" ? picked : newName;
    if (mode === "new" && !BATCH_LIBRARY.includes(batch)) BATCH_LIBRARY.push(batch);
    onConfirm(batch);
    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 = myFormsByBatch.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_10"
                  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, { BatchPicker });
