// RMItems.jsx — Master Data › Repair & Maintenance Items.
// The catalog behind the R&M module: the fixed service-item list (with its
// locked countdown interval) that drives the Maintenance Schedule, plus the
// repair issue templates that populate the New Ticket dropdown. Admin edits
// here; the Operations › Repair & Maintenance screen consumes these lists.

const RM_ISSUE_TEMPLATES = [
  'Hydraulic leak',
  'Engine fault',
  'Slew gear noise',
  'Outrigger drift',
  'Boom inspection',
  'Electrical fault',
  'Tyre / wheel',
  'Other (see Info)',
];

function intervalBand(months) {
  if (months <= 3) return { label: 'Frequent', cls: 'red' };
  if (months <= 12) return { label: 'Routine', cls: 'yellow' };
  return { label: 'Long-cycle', cls: 'green' };
}

function RMItemsPage({ role }) {
  const isAdmin = role === 'Admin';
  const [items, setItems] = React.useState(SERVICE_ITEMS.map((s, i) => ({ id: 'RMI-' + String(i + 1).padStart(2, '0'), ...s })));
  const [issues] = React.useState(RM_ISSUE_TEMPLATES);
  const [q, setQ] = React.useState('');
  const [showAdd, setShowAdd] = React.useState(false);
  const [draft, setDraft] = React.useState({ item: '', months: 6 });
  const [editing, setEditing] = React.useState(null);
  const [editDraft, setEditDraft] = React.useState(null);

  const query = q.trim().toLowerCase();
  const rows = items.filter(s => !query || s.item.toLowerCase().includes(query) || String(s.months).includes(query));

  const syncGlobal = (next) => {
    setItems(next);
    // Keep the global catalog in sync so the R&M schedule + interval lookup update.
    SERVICE_ITEMS.length = 0;
    next.forEach(x => SERVICE_ITEMS.push({ item: x.item, months: x.months }));
    Object.keys(SERVICE_INTERVAL_MONTHS).forEach(k => delete SERVICE_INTERVAL_MONTHS[k]);
    next.forEach(x => { SERVICE_INTERVAL_MONTHS[x.item] = x.months; });
  };

  const addItem = () => {
    if (!draft.item.trim()) return;
    const id = 'RMI-' + String(items.length + 1).padStart(2, '0');
    const next = [...items, { id, item: draft.item.trim(), months: Number(draft.months) || 6 }];
    syncGlobal(next);
    setDraft({ item: '', months: 6 });
    setShowAdd(false);
  };

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

  const saveEdit = () => {
    window.askAdminPassword('Edit R&M item · ' + editDraft.item, () => {
      syncGlobal(items.map(s => s.id === editDraft.id ? { ...editDraft, months: Number(editDraft.months) || 1 } : s));
      setEditing(null); setEditDraft(null);
    });
  };

  const deleteItem = (s) => {
    window.askAdminPassword('Delete R&M item · ' + s.item, () => {
      syncGlobal(items.filter(x => x.id !== s.id));
    });
  };

  return (
    <div className="page">
      <div className="note-banner">
        <Layers size={16} style={{color: 'var(--color-navy)'}}/>
        <div>
          <strong>Repair &amp; Maintenance Items</strong> — the master catalog behind the workshop. <strong>Service items</strong> carry a fixed countdown interval and drive the Maintenance Schedule on every crane; <strong>repair issue types</strong> populate the New Ticket form. Manage them here in Master Data — the <strong>Operations › Repair &amp; Maintenance</strong> screen consumes these lists.
        </div>
      </div>

      <div className="page-actions" style={{marginBottom: 16}}>
        <div style={{fontSize: 13, color: 'var(--color-grey-600)'}}>
          {items.length} service item{items.length === 1 ? '' : 's'} · {issues.length} repair issue type{issues.length === 1 ? '' : 's'}
        </div>
        {isAdmin ? (
          <button className="btn btn--primary" onClick={() => setShowAdd(true)}>
            <Plus size={16}/> Add Service Item
          </button>
        ) : <span className="restricted-tag"><Lock size={11}/> Admin only</span>}
      </div>

      {/* Search */}
      <div style={{position: 'relative', maxWidth: 480, margin: '0 0 16px'}}>
        <Search size={18} style={{position: 'absolute', left: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)', pointerEvents: 'none'}}/>
        <input
          value={q}
          onChange={e => setQ(e.target.value)}
          placeholder="Search service items by name or interval..."
          className="input"
          style={{height: 46, paddingLeft: 44, paddingRight: q ? 40 : 14, width: '100%', fontSize: 15, borderRadius: 12}}/>
        {q ? (
          <button type="button" onClick={() => setQ('')} aria-label="Clear search"
            style={{position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', width: 28, height: 28, borderRadius: 7, border: 'none', background: 'var(--color-grey-100)', color: 'var(--color-grey-600)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
            <X size={15}/>
          </button>
        ) : null}
      </div>

      {/* Service items catalog */}
      <div className="card" style={{marginBottom: 20}}>
        <div className="card__header">
          <div>
            <h3 className="card__title">Service Items</h3>
            <div className="card__sub">Fixed countdown interval (months) · applied to every crane</div>
          </div>
          <span className="status status--blue">{rows.length} shown</span>
        </div>
        <div className="card__body" style={{padding: 0, overflowX: 'auto'}}>
          <table className="table">
            <thead>
              <tr>
                <th>ID</th><th>Service Item</th><th>Interval (fixed)</th><th>Frequency</th>
                {isAdmin ? <th style={{textAlign: 'right'}}>Actions</th> : null}
              </tr>
            </thead>
            <tbody>
              {rows.map(s => {
                const band = intervalBand(s.months);
                return (
                  <tr key={s.id}>
                    <td style={{fontFamily: 'monospace', fontSize: 12, color: 'var(--color-grey-600)'}}>{s.id}</td>
                    <td>
                      {editing === s.id ? (
                        <input className="input" value={editDraft.item} onChange={e => setEditDraft({...editDraft, item: e.target.value})}/>
                      ) : (
                        <span style={{fontWeight: 600}}>{s.item}</span>
                      )}
                    </td>
                    <td>
                      {editing === s.id ? (
                        <div style={{display: 'flex', alignItems: 'center', gap: 6}}>
                          <input className="input" type="number" min="1" style={{width: 90}} value={editDraft.months} onChange={e => setEditDraft({...editDraft, months: e.target.value})}/>
                          <span style={{fontSize: 13, color: 'var(--color-grey-500)'}}>months</span>
                        </div>
                      ) : (
                        <span style={{fontFamily: 'monospace', display: 'inline-flex', alignItems: 'center', gap: 5}}>
                          {s.months} mo <Lock size={11} style={{color: 'var(--color-grey-400)'}}/>
                        </span>
                      )}
                    </td>
                    <td><span className={"status status--" + band.cls}>{band.label}</span></td>
                    {isAdmin ? (
                      <td style={{textAlign: 'right'}}>
                        {editing === s.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={() => startEdit(s)}>
                              <Edit size={12}/> Modify
                            </button>
                            <button className="btn btn--ghost" style={{padding: '4px 10px', fontSize: 12, color: '#dc2626'}} onClick={() => deleteItem(s)}>
                              <Trash2 size={12}/>
                            </button>
                          </div>
                        )}
                      </td>
                    ) : null}
                  </tr>
                );
              })}
              {rows.length === 0 ? (
                <tr><td colSpan={isAdmin ? 5 : 4} style={{padding: 28, textAlign: 'center', color: 'var(--color-grey-500)', fontSize: 14}}>No service items match “{q}”</td></tr>
              ) : null}
            </tbody>
          </table>
        </div>
        <div style={{padding: 12, fontSize: 12, color: 'var(--color-grey-500)', borderTop: '1px solid var(--color-grey-200)', display: 'flex', alignItems: 'center', gap: 6}}>
          <Lock size={11}/> Interval is fixed per item and applies fleet-wide. Changing it here updates the countdown on every scheduled crane.
        </div>
      </div>

      {/* Repair issue templates */}
      <div className="card">
        <div className="card__header">
          <div>
            <h3 className="card__title">Repair Issue Types</h3>
            <div className="card__sub">Templates shown in the New Ticket dropdown</div>
          </div>
          <span className="status status--gray">{issues.length}</span>
        </div>
        <div className="card__body">
          <div style={{display: 'flex', flexWrap: 'wrap', gap: 8}}>
            {issues.map(issue => (
              <span key={issue} style={{display: 'inline-flex', alignItems: 'center', gap: 6, padding: '7px 12px', background: 'var(--color-grey-50)', border: '1px solid var(--color-grey-200)', borderRadius: 999, fontSize: 13, color: 'var(--color-grey-800)', fontWeight: 500}}>
                <Wrench size={12} style={{color: 'var(--color-grey-500)'}}/> {issue}
              </span>
            ))}
          </div>
        </div>
      </div>

      {/* Add service item 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 Service Item</div>
              <button className="install-banner__close" onClick={() => setShowAdd(false)}><X size={18}/></button>
            </div>
            <div className="field" style={{marginBottom: 12}}>
              <label>Service item name *</label>
              <input className="input" value={draft.item} onChange={e => setDraft({...draft, item: e.target.value})} placeholder="e.g. Brake Fluid" autoFocus/>
            </div>
            <div className="field" style={{marginBottom: 16}}>
              <label>Fixed interval (months)</label>
              <input className="input" type="number" min="1" value={draft.months} onChange={e => setDraft({...draft, months: e.target.value})}/>
              <div style={{fontSize: 12, color: 'var(--color-grey-500)', marginTop: 6}}>This becomes the locked countdown period applied to every crane.</div>
            </div>
            <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.item.trim()} onClick={addItem}>
                <Plus size={14}/> Create Item
              </button>
            </div>
          </div>
        </div>
      ) : null}
    </div>
  );
}

Object.assign(window, { RMItemsPage });
