// Tools.jsx — Admin-managed list of site tools / equipment.
// Lives under Administration → Tools. The list feeds the multi-select
// dropdown in Create Booking ("Tools to bring on site").

function ToolsPage({ role }) {
  const isAdmin = role === 'Admin';
  const [tools, setTools] = React.useState(TOOLS);
  const [showAdd, setShowAdd] = React.useState(false);
  const [draft, setDraft] = React.useState({ name: '', category: 'Rigging', default: false });
  const [editing, setEditing] = React.useState(null); // id of row being edited
  const [editDraft, setEditDraft] = React.useState(null);

  const grouped = {};
  tools.forEach(t => { (grouped[t.category] = grouped[t.category] || []).push(t); });

  const addTool = () => {
    if (!draft.name.trim()) return;
    const id = 'T-' + String(tools.length + 1).padStart(2, '0');
    const next = [...tools, { id, ...draft, name: draft.name.trim() }];
    setTools(next);
    TOOLS.length = 0; next.forEach(x => TOOLS.push(x)); // mutate global so Create Booking picks it up
    setDraft({ name: '', category: 'Rigging', default: false });
    setShowAdd(false);
  };

  const startEdit = (t) => { setEditing(t.id); setEditDraft({...t}); };

  const saveEdit = () => {
    window.askAdminPassword('Edit tool · ' + editDraft.name, () => {
      const next = tools.map(t => t.id === editDraft.id ? editDraft : t);
      setTools(next);
      TOOLS.length = 0; next.forEach(x => TOOLS.push(x));
      setEditing(null); setEditDraft(null);
    });
  };

  const deleteTool = (t) => {
    window.askAdminPassword('Delete tool · ' + t.name, () => {
      const next = tools.filter(x => x.id !== t.id);
      setTools(next);
      TOOLS.length = 0; next.forEach(x => TOOLS.push(x));
    });
  };

  const toggleDefault = (t) => {
    window.askAdminPassword('Toggle default · ' + t.name, () => {
      const next = tools.map(x => x.id === t.id ? {...x, default: !x.default} : x);
      setTools(next);
      TOOLS.length = 0; next.forEach(x => TOOLS.push(x));
    });
  };

  return (
    <div className="page">
      <div className="note-banner">
        <Wrench size={16} style={{color: 'var(--color-navy)'}}/>
        <div>
          <strong>Site Tools &amp; Equipment</strong> — items that operators may need to bring to a job site. Admin manages this list; it appears as a multi-select dropdown in <strong>Create Booking</strong>. Tools marked <em>default</em> are pre-checked on every new booking.
        </div>
      </div>

      <div className="page-actions" style={{marginBottom: 16}}>
        <div style={{fontSize: 13, color: 'var(--color-grey-600)'}}>
          {tools.length} tool{tools.length === 1 ? '' : 's'} · grouped by category · {tools.filter(t => t.default).length} marked default
        </div>
        {isAdmin ? (
          <button className="btn btn--primary" onClick={() => setShowAdd(true)}>
            <Plus size={16}/> Add Tool
          </button>
        ) : <span className="restricted-tag"><Lock size={11}/> Admin only</span>}
      </div>

      {/* Tools grouped by category */}
      {Object.entries(grouped).map(([cat, items]) => (
        <div className="card" key={cat} style={{marginBottom: 16}}>
          <div className="card__header">
            <div>
              <h3 className="card__title">{cat}</h3>
              <div className="card__sub">{items.length} item{items.length === 1 ? '' : 's'}</div>
            </div>
          </div>
          <div className="card__body" style={{padding: 0}}>
            <table className="table">
              <thead>
                <tr>
                  <th>ID</th><th>Tool Name</th><th>Default</th><th style={{textAlign: 'right'}}>Actions</th>
                </tr>
              </thead>
              <tbody>
                {items.map(t => (
                  <tr key={t.id}>
                    <td style={{fontFamily: 'monospace', fontSize: 12, color: 'var(--color-grey-600)'}}>{t.id}</td>
                    <td>
                      {editing === t.id ? (
                        <input className="input" value={editDraft.name} onChange={e => setEditDraft({...editDraft, name: e.target.value})}/>
                      ) : (
                        <span style={{fontWeight: 600}}>{t.name}</span>
                      )}
                    </td>
                    <td>
                      {editing === t.id ? (
                        <label style={{display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--color-grey-600)'}}>
                          <input type="checkbox" checked={editDraft.default} onChange={e => setEditDraft({...editDraft, default: e.target.checked})}/>
                          Default
                        </label>
                      ) : (
                        <span className={"status status--" + (t.default ? 'green' : 'gray')}>{t.default ? 'Default' : 'Optional'}</span>
                      )}
                    </td>
                    <td style={{textAlign: 'right'}}>
                      {isAdmin ? (
                        editing === t.id ? (
                          <div style={{display: 'flex', gap: 4, justifyContent: 'flex-end'}}>
                            <button className="btn btn--ghost" style={{padding: '4px 10px', fontSize: 12}} onClick={() => { setEditing(null); setEditDraft(null); }}>Cancel</button>
                            <button className="btn btn--primary" style={{padding: '4px 10px', fontSize: 12}} onClick={saveEdit}>Save</button>
                          </div>
                        ) : (
                          <div style={{display: 'flex', gap: 4, justifyContent: 'flex-end'}}>
                            <button className="btn btn--ghost" style={{padding: '4px 10px', fontSize: 12}} onClick={() => toggleDefault(t)} title="Toggle whether this tool is pre-checked on new bookings">
                              {t.default ? 'Unmark default' : 'Mark default'}
                            </button>
                            <button className="btn btn--ghost" style={{padding: '4px 10px', fontSize: 12}} onClick={() => startEdit(t)}>
                              <Edit size={12}/> Modify
                            </button>
                            <button className="btn btn--ghost" style={{padding: '4px 10px', fontSize: 12, color: '#dc2626'}} onClick={() => deleteTool(t)}>
                              <Trash2 size={12}/>
                            </button>
                          </div>
                        )
                      ) : null}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      ))}

      {/* Add tool modal */}
      {showAdd ? (
        <div className="install-modal" onClick={() => setShowAdd(false)}>
          <div className="install-modal__card" onClick={(e) => e.stopPropagation()} style={{maxWidth: 480}}>
            <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14}}>
              <div style={{fontWeight: 700, fontSize: 18, color: 'var(--color-navy)'}}>Add Tool</div>
              <button className="install-banner__close" onClick={() => setShowAdd(false)}><X size={18}/></button>
            </div>
            <div className="field" style={{marginBottom: 12}}>
              <label>Tool name *</label>
              <input className="input" value={draft.name} onChange={e => setDraft({...draft, name: e.target.value})} placeholder="e.g. Spreader Bar — 10t" autoFocus/>
            </div>
            <div className="field" style={{marginBottom: 12}}>
              <label>Category</label>
              <select className="select" value={draft.category} onChange={e => setDraft({...draft, category: e.target.value})}>
                {['Stability', 'Rigging', 'Safety', 'Comms', 'Fuel', 'Other'].map(c => <option key={c}>{c}</option>)}
              </select>
            </div>
            <label style={{display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--color-grey-700)', marginBottom: 16}}>
              <input type="checkbox" checked={draft.default} onChange={e => setDraft({...draft, default: e.target.checked})}/>
              Mark as <strong>default</strong> — pre-check this tool on every new booking
            </label>
            <div style={{display: 'flex', gap: 8, justifyContent: 'flex-end'}}>
              <button className="btn btn--ghost" onClick={() => setShowAdd(false)}>Cancel</button>
              <button className="btn btn--primary" disabled={!draft.name.trim()} onClick={addTool}>
                <Plus size={14}/> Create Tool
              </button>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}

Object.assign(window, { ToolsPage });
