/* Truong So CRM — Add Customer Wizard (multi-step sales intake) */
const { useState: useWS } = React;

const SOURCES = window.CRM_SOURCES;

function Field({ label, required, error, children, hint, full }) {
  return (
    <div className={"field" + (full ? " full" : "")}>
      <label className="fLabel">{label}{required && <span className="req">*</span>}</label>
      {children}
      {hint && !error && <div className="fHint">{hint}</div>}
      {error && <div className="fError">{error}</div>}
    </div>
  );
}

function AddCustomerWizard({ onClose, onSave, defaultPipeline }) {
  const [step, setStep] = useWS(0);
  const [touched, setTouched] = useWS(false);
  const [form, setForm] = useWS({
    type: "company",
    name: "", company: "", title: "", email: "", phone: "",
    location: "", source: "Website", owner: "u1", status: "new", tags: [],
    createDeal: true,
    dealTitle: "", dealValue: "", pipeline: defaultPipeline || "sales", stage: "lead",
    expClose: "", notes: "",
  });
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const toggleTag = (t) => setForm(f => ({ ...f, tags: f.tags.includes(t) ? f.tags.filter(x => x !== t) : [...f.tags, t] }));

  const steps = ["Thông tin khách hàng", "Cơ hội bán hàng", "Xác nhận"];
  const emailOk = form.email === "" || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email);
  const phoneOk = form.phone.replace(/\D/g, "").length >= 9;

  const step0Errors = {
    name: !form.name.trim() ? "Vui lòng nhập tên" : "",
    company: form.type === "company" && !form.company.trim() ? "Vui lòng nhập công ty" : "",
    phone: !phoneOk ? "Số điện thoại không hợp lệ" : "",
    email: !emailOk ? "Email không hợp lệ" : "",
  };
  const step0Valid = !step0Errors.name && !step0Errors.company && !step0Errors.phone && !step0Errors.email;

  const dealValueNum = Number(String(form.dealValue).replace(/\D/g, "")) || 0;
  const step1Valid = !form.createDeal || (form.dealTitle.trim() && dealValueNum > 0);

  function next() {
    if (step === 0) { setTouched(true); if (!step0Valid) return; setTouched(false); }
    if (step === 1 && !step1Valid) { setTouched(true); return; }
    setStep(s => Math.min(2, s + 1));
  }
  function back() { setStep(s => Math.max(0, s - 1)); }

  function submit() {
    onSave({
      contact: {
        id: "c" + Date.now(),
        name: form.name.trim(), company: form.company.trim() || "—", title: form.title.trim() || "—",
        email: form.email.trim() || "—", phone: form.phone.trim(), owner: form.owner,
        status: form.status, source: form.source, tags: form.tags, location: form.location.trim() || "—",
        last: new Date("2026-06-06T09:00:00").toISOString(), openValue: dealValueNum, deals: form.createDeal ? 1 : 0,
      },
      deal: form.createDeal ? {
        id: "d" + Date.now(), pipeline: form.pipeline, stage: form.stage,
        title: form.dealTitle.trim(), company: form.company.trim() || form.name.trim(),
        value: dealValueNum, owner: form.owner, label: form.tags[0] || null,
        next: form.expClose ? new Date(form.expClose).toISOString() : new Date("2026-06-13").toISOString(),
        activities: 0, idleDays: 0,
      } : null,
    });
  }

  const owners = window.CRM_OWNERS;
  const stages = window.CRM_STAGES[form.pipeline];

  return (
    <>
      <div className="drawerScrim" onClick={onClose}></div>
      <div className="wizard" role="dialog">
        <div className="wizHead">
          <div>
            <div className="wizKicker">Nhập khách hàng mới</div>
            <h2 className="wizTitle">{steps[step]}</h2>
          </div>
          <button className="iconBtn" onClick={onClose} aria-label="Đóng">✕</button>
        </div>

        <div className="stepper">
          {steps.map((s, i) => (
            <div key={i} className={"stepItem" + (i === step ? " active" : "") + (i < step ? " done" : "")}>
              <div className="stepDot">{i < step ? "✓" : i + 1}</div>
              <span className="stepName">{s}</span>
              {i < steps.length - 1 && <div className="stepLine"></div>}
            </div>
          ))}
        </div>

        <div className="wizBody">
          {step === 0 && (
            <>
              <div className="typeToggle">
                <button className={"ttBtn" + (form.type === "company" ? " on" : "")} onClick={() => set("type", "company")}>
                  <svg viewBox="0 0 24 24" width="18" fill="none" stroke="currentColor" strokeWidth="1.8"><path d="M3 21V7l6-3v17M9 21V11l8-4v14M3 21h18M13 21V3l8 3v15"/></svg>Doanh nghiệp
                </button>
                <button className={"ttBtn" + (form.type === "person" ? " on" : "")} onClick={() => set("type", "person")}>
                  <svg viewBox="0 0 24 24" width="18" fill="none" stroke="currentColor" strokeWidth="1.8"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0116 0"/></svg>Cá nhân
                </button>
              </div>
              <div className="formGrid">
                <Field label="Họ và tên" required error={touched && step0Errors.name}>
                  <input className="inp" value={form.name} onChange={e => set("name", e.target.value)} placeholder="VD: Nguyễn Văn A" />
                </Field>
                <Field label="Chức vụ"><input className="inp" value={form.title} onChange={e => set("title", e.target.value)} placeholder="VD: Giám đốc" /></Field>
                {form.type === "company" && (
                  <Field label="Công ty" required error={touched && step0Errors.company} full>
                    <input className="inp" value={form.company} onChange={e => set("company", e.target.value)} placeholder="Tên công ty" />
                  </Field>
                )}
                <Field label="Email" error={touched && step0Errors.email}>
                  <input className="inp" value={form.email} onChange={e => set("email", e.target.value)} placeholder="email@congty.vn" />
                </Field>
                <Field label="Số điện thoại" required error={touched && step0Errors.phone}>
                  <input className="inp" value={form.phone} onChange={e => set("phone", e.target.value)} placeholder="09xx xxx xxx" />
                </Field>
                <Field label="Khu vực"><input className="inp" value={form.location} onChange={e => set("location", e.target.value)} placeholder="Tỉnh / Thành phố" /></Field>
                <Field label="Nguồn khách">
                  <select className="inp" value={form.source} onChange={e => set("source", e.target.value)}>
                    {SOURCES.map(s => <option key={s}>{s}</option>)}
                  </select>
                </Field>
                <Field label="Người phụ trách" full>
                  <div className="ownerPick">
                    {owners.map(o => (
                      <button key={o.id} className={"ownerOpt" + (form.owner === o.id ? " on" : "")} onClick={() => set("owner", o.id)}>
                        <Avatar owner={o} size={24} />{o.name}
                      </button>
                    ))}
                  </div>
                </Field>
                <Field label="Nhãn" full>
                  <div className="tagPick">
                    {Object.entries(window.CRM_LABELS).map(([k, v]) => (
                      <button key={k} className={"tagOpt" + (form.tags.includes(k) ? " on" : "")}
                        style={{ "--h": v.hue }} onClick={() => toggleTag(k)}>{v.name}</button>
                    ))}
                  </div>
                </Field>
              </div>
            </>
          )}

          {step === 1 && (
            <>
              <label className="dealToggle">
                <input type="checkbox" checked={form.createDeal} onChange={e => set("createDeal", e.target.checked)} />
                <span className="dtBox"></span>
                <span><b>Tạo cơ hội bán hàng kèm theo</b><br/><span className="dtSub">Thêm deal vào pipeline ngay khi lưu khách hàng</span></span>
              </label>
              {form.createDeal && (
                <div className="formGrid" style={{ marginTop: 18 }}>
                  <Field label="Tên cơ hội" required error={touched && !form.dealTitle.trim() ? "Nhập tên cơ hội" : ""} full>
                    <input className="inp" value={form.dealTitle} onChange={e => set("dealTitle", e.target.value)} placeholder="VD: Triển khai phần mềm quản lý" />
                  </Field>
                  <Field label="Giá trị (₫)" required error={touched && dealValueNum <= 0 ? "Nhập giá trị" : ""}>
                    <input className="inp" value={form.dealValue ? Number(String(form.dealValue).replace(/\D/g,"")).toLocaleString("vi-VN") : ""}
                      onChange={e => set("dealValue", e.target.value)} placeholder="0" inputMode="numeric" />
                  </Field>
                  <Field label="Ngày dự kiến chốt"><input className="inp" type="date" value={form.expClose} onChange={e => set("expClose", e.target.value)} /></Field>
                  <Field label="Pipeline">
                    <select className="inp" value={form.pipeline} onChange={e => { set("pipeline", e.target.value); set("stage", window.CRM_STAGES[e.target.value][0].id); }}>
                      {window.CRM_PIPELINES.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                    </select>
                  </Field>
                  <Field label="Giai đoạn">
                    <select className="inp" value={form.stage} onChange={e => set("stage", e.target.value)}>
                      {stages.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
                    </select>
                  </Field>
                </div>
              )}
              <Field label="Ghi chú" full>
                <textarea className="inp txt" rows="3" value={form.notes} onChange={e => set("notes", e.target.value)} placeholder="Bối cảnh, nhu cầu, lịch hẹn tiếp theo…"></textarea>
              </Field>
            </>
          )}

          {step === 2 && (
            <div className="reviewCard">
              <div className="reviewRow"><span>Khách hàng</span><b>{form.name || "—"}</b></div>
              <div className="reviewRow"><span>Công ty</span><b>{form.company || "—"} {form.title && "· " + form.title}</b></div>
              <div className="reviewRow"><span>Liên hệ</span><b>{form.phone || "—"}{form.email && " · " + form.email}</b></div>
              <div className="reviewRow"><span>Khu vực · Nguồn</span><b>{form.location || "—"} · {form.source}</b></div>
              <div className="reviewRow"><span>Phụ trách</span><b>{ownerById(form.owner).name}</b></div>
              {form.tags.length > 0 && <div className="reviewRow"><span>Nhãn</span><span className="dealLabels" style={{display:'flex',gap:6}}>{form.tags.map(t => <Label key={t} id={t} />)}</span></div>}
              <div className="reviewDivide"></div>
              {form.createDeal ? (
                <>
                  <div className="reviewRow"><span>Cơ hội</span><b>{form.dealTitle || "—"}</b></div>
                  <div className="reviewRow"><span>Giá trị</span><b style={{color:'var(--primary)'}}>{dealValueNum.toLocaleString("vi-VN")} ₫</b></div>
                  <div className="reviewRow"><span>Pipeline · Giai đoạn</span><b>{window.CRM_PIPELINES.find(p=>p.id===form.pipeline).name} · {stages.find(s=>s.id===form.stage).name}</b></div>
                </>
              ) : <div className="reviewRow"><span>Cơ hội</span><b>Không tạo deal</b></div>}
            </div>
          )}
        </div>

        <div className="wizFoot">
          {step > 0 ? <button className="btn ghost" onClick={back}>Quay lại</button> : <button className="btn ghost" onClick={onClose}>Huỷ</button>}
          <div className="wizFootRight">
            <span className="wizProg">Bước {step + 1}/3</span>
            {step < 2
              ? <button className="btn primary" onClick={next}>Tiếp tục</button>
              : <button className="btn primary" onClick={submit}>Lưu khách hàng</button>}
          </div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { AddCustomerWizard });
