/* ============================================================
   Service Type Management — per MTG4 §2.1
   ============================================================
   Admin can create / edit / delete service types. Each type has:
   - 3-letter Condense code (AUD, LMR, AUP, OTH, …)
   - Name
   - Description (shown as tooltip in Project form)
   - Sub-details (Year, Quarterly, etc.) — optional
   ============================================================ */

/* ====== Add / Edit Service Type modal — just Name + Description ======
   Code (AUD / LMR / …) is derived from the name on create and preserved
   on edit; sub-details are kept on the underlying record but not
   exposed on this simplified form. */
const ServiceTypeFormModal = ({ initial, existingCodes, onClose, onSave }) => {
  const isEdit = !!initial;
  const [name, setName] = React.useState(initial?.name || "");
  const [desc, setDesc] = React.useState(initial?.desc || "");

  const nameValid = name.trim().length >= 2;
  const descValid = desc.trim().length >= 3;
  const canSave = nameValid && descValid;

  /* Auto-derive a 3-letter code from the display name. Falls back to a
     short random suffix when the cleaned name has too few letters. */
  const deriveCode = (n) => {
    const letters = n.toUpperCase().replace(/[^A-Z]/g, "");
    if (letters.length >= 3) return letters.slice(0, 3);
    const base = (letters + "XXX").slice(0, 3);
    let candidate = base;
    let i = 1;
    while (existingCodes.includes(candidate)) {
      candidate = (letters + i).slice(0, 3).toUpperCase();
      i++;
      if (i > 99) break;
    }
    return candidate;
  };

  const handleSave = () => {
    const cleanName = name.trim();
    const cleanDesc = desc.trim();
    if (isEdit) {
      onSave({ name: cleanName, desc: cleanDesc });
    } else {
      const code = deriveCode(cleanName);
      onSave({ code, name: cleanName, desc: cleanDesc, details: [] });
    }
  };

  return (
    <div className="modal-veil" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{maxWidth: 540, width: "94vw"}}>
        <div className="modal-head">
          <div style={{width:32,height:32,borderRadius:8,background:"var(--accent-soft)",color:"var(--accent-ink)",display:"grid",placeItems:"center"}}>
            <Icon n={isEdit ? "edit-3" : "plus"} s={16}/>
          </div>
          <h3>{isEdit ? `Edit service type — ${initial.name}` : "New service type"}</h3>
        </div>
        <div className="modal-body">
          <div className="field">
            <label>Name <span className="req">*</span></label>
            <input type="text" value={name} onChange={e=>setName(e.target.value)} placeholder="e.g. Audit" autoFocus/>
          </div>

          <div className="field" style={{marginBottom:0}}>
            <label>Description <span className="req">*</span></label>
            <textarea
              value={desc} onChange={e=>setDesc(e.target.value)}
              placeholder="What this engagement covers, what it produces, when to use it."
              style={{minHeight:100}}
            />
          </div>
        </div>
        <div className="modal-foot">
          <button className="btn" onClick={onClose}>Cancel</button>
          <button className="btn primary" disabled={!canSave} onClick={handleSave}>
            <Icon n="check" s={13}/> {isEdit ? "Save changes" : "Create service type"}
          </button>
        </div>
      </div>
    </div>
  );
};

/* ====== Delete confirmation ====== */
const DeleteServiceTypeModal = ({ st, usedCount, onClose, onConfirm }) => (
  <div className="modal-veil" onClick={onClose}>
    <div className="modal" onClick={e=>e.stopPropagation()}>
      <div className="modal-head">
        <div style={{width:32,height:32,borderRadius:8,background:"var(--danger-soft)",color:"var(--danger-ink)",display:"grid",placeItems:"center"}}>
          <Icon n="trash" s={16}/>
        </div>
        <h3>Delete service type?</h3>
      </div>
      <div className="modal-body">
        <p style={{margin:"0 0 12px"}}>
          <b>{st.name}</b> (<span className="mono">{st.code}</span>) will be removed from the catalog.
        </p>
        {usedCount > 0 ? (
          <div className="banner danger">
            <div className="b-ico"><Icon n="alert-triangle" s={15}/></div>
            <div className="b-body">
              <span className="b-title">Used by {usedCount} project{usedCount>1?"s":""}</span>
              Existing projects keep this label, but new projects can't pick this type. Recommended: rename to "(deprecated)" instead of deleting.
            </div>
          </div>
        ) : (
          <div className="banner muted">
            <div className="b-ico"><Icon n="info" s={14}/></div>
            <div className="b-body">Not used by any project — safe to delete.</div>
          </div>
        )}
      </div>
      <div className="modal-foot">
        <button className="btn" onClick={onClose}>Cancel</button>
        <button className="btn danger solid" onClick={onConfirm}>
          <Icon n="trash" s={13}/> Delete
        </button>
      </div>
    </div>
  </div>
);

/* ====== Service Type Screen ====== */
const ServiceTypeScreen = ({ state, nav }) => {
  const [catalog, setCatalog] = React.useState(SERVICE_TYPE_CATALOG.slice());
  const [modal, setModal] = React.useState(null); // {type:'add'} | {type:'edit',st} | {type:'delete',st}

  const usage = React.useMemo(() => {
    const map = {};
    state.projects.forEach(p => {
      const st = catalog.find(s => s.name === p.serviceType);
      if (st) map[st.code] = (map[st.code] || 0) + 1;
    });
    return map;
  }, [catalog, state.projects]);

  const handleAdd = (payload) => {
    setCatalog(prev => [...prev, payload]);
    SERVICE_TYPE_CATALOG.push(payload);
    nav.toast(`Service type ${payload.code} created`, "ok");
    nav.log && nav.log({ action:"edit", obj:`Service Type ${payload.code}`, detail:`Created service type "${payload.name}"`, severity:"critical" });
    setModal(null);
  };

  const handleEdit = (oldCode, payload) => {
    setCatalog(prev => prev.map(s => s.code === oldCode ? { ...s, ...payload } : s));
    const idx = SERVICE_TYPE_CATALOG.findIndex(s => s.code === oldCode);
    if (idx >= 0) SERVICE_TYPE_CATALOG[idx] = { ...SERVICE_TYPE_CATALOG[idx], ...payload };
    nav.toast(`Service type ${oldCode} updated`, "ok");
    nav.log && nav.log({ action:"edit", obj:`Service Type ${oldCode}`, detail:`Updated · ${Object.keys(payload).join(", ")}`, severity:"critical" });
    setModal(null);
  };

  const handleDelete = (code) => {
    setCatalog(prev => prev.filter(s => s.code !== code));
    const idx = SERVICE_TYPE_CATALOG.findIndex(s => s.code === code);
    if (idx >= 0) SERVICE_TYPE_CATALOG.splice(idx, 1);
    nav.toast(`Service type ${code} deleted`, "warn");
    nav.log && nav.log({ action:"delete", obj:`Service Type ${code}`, detail:`Deleted service type`, severity:"critical" });
    setModal(null);
  };

  return (
    <>
      <div className="page-head">
        <div className="page-title-row">
          <h1 className="page-title">Service Types</h1>
          <span className="badge mono">{catalog.length} types</span>
          <div className="page-actions">
            <button className="btn primary" onClick={()=>setModal({type:"add"})}>
              <Icon n="plus" s={13}/> New service type
            </button>
          </div>
        </div>
      </div>

      <div className="page-body">
        {catalog.length === 0 ? (
          <div className="card">
            <EmptyState icon="layers" title="No service types yet" sub="Add at least one before users can create projects." cta={<button className="btn primary" onClick={()=>setModal({type:"add"})}><Icon n="plus" s={13}/> New service type</button>}/>
          </div>
        ) : (
          <div className="card">
            <table className="tbl">
              <thead><tr>
                <th style={{width:220}}>Name</th>
                <th>Description</th>
                <th style={{width:100,textAlign:"center"}}>Used by</th>
                <th style={{width:140,textAlign:"right"}}></th>
              </tr></thead>
              <tbody>
                {catalog.map(st => {
                  const used = usage[st.code] || 0;
                  const isDefault = ["AUD","LMR","AUP","OTH"].includes(st.code);
                  return (
                    <tr key={st.code}>
                      <td><b>{st.name}</b></td>
                      <td>
                        <div style={{fontSize:12.5,color:"var(--ink-2)",lineHeight:1.5}}>
                          {st.desc || <span className="muted">—</span>}
                        </div>
                      </td>
                      <td style={{textAlign:"center"}}>
                        {used > 0
                          ? <span className="sbadge accent">{used}</span>
                          : <span className="muted" style={{fontSize:12}}>—</span>}
                      </td>
                      <td style={{textAlign:"right"}}>
                        <div style={{display:"inline-flex",gap:6}}>
                          <button className="btn sm" onClick={()=>setModal({type:"edit", st})}>
                            <Icon n="edit-3" s={11}/> Edit
                          </button>
                          <button
                            className="btn sm danger"
                            disabled={isDefault && used > 0}
                            title={isDefault && used > 0 ? "Default service type in use — cannot delete" : "Delete"}
                            onClick={()=>setModal({type:"delete", st, used})}>
                            <Icon n="trash" s={11}/>
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {modal?.type === "add" && (
        <ServiceTypeFormModal
          existingCodes={catalog.map(s => s.code)}
          onClose={()=>setModal(null)}
          onSave={handleAdd}
        />
      )}
      {modal?.type === "edit" && (
        <ServiceTypeFormModal
          initial={modal.st}
          existingCodes={catalog.map(s => s.code)}
          onClose={()=>setModal(null)}
          onSave={(payload)=>handleEdit(modal.st.code, payload)}
        />
      )}
      {modal?.type === "delete" && (
        <DeleteServiceTypeModal st={modal.st} usedCount={modal.used || 0}
          onClose={()=>setModal(null)}
          onConfirm={()=>handleDelete(modal.st.code)}
        />
      )}
    </>
  );
};

Object.assign(window, { ServiceTypeScreen, ServiceTypeFormModal, DeleteServiceTypeModal });
