// AddRepair.jsx — Operator-facing "Add Repair" form.
// Lets an Operator (or Rigger) report a fault on the machine they run, so the
// workshop sees it without a phone call. Deliberately simpler than the
// Admin/Mechanic R&M ticket form (no cost / mechanic / supplier fields) — an
// operator just says WHICH machine, WHAT is wrong, HOW bad, and adds a photo.

// Problem areas an operator picks from (plain language, not workshop jargon).
const REPAIR_AREAS = [
  'Engine',
  'Hydraulics',
  'Boom & winch',
  'Slew / rotation',
  'Outriggers',
  'Brakes',
  'Tyres / wheels',
  'Electrical / lights',
  'Cabin / controls',
  'Other (describe below)',
];

// Severity in operator language — how much it stops the job.
const SEVERITY = [
  { id: 'Low',    label: 'Low',    note: 'Can still work', status: 'gray' },
  { id: 'Medium', label: 'Medium', note: 'Affecting work', status: 'yellow' },
  { id: 'High',   label: 'High',   note: 'Cannot operate', status: 'red' },
];

function severityStatus(sev) {
  return (SEVERITY.find(s => s.id === sev) || {}).status || 'gray';
}

// Map a machine id (or freeform machine string) to a readable label.
function repairMachineLabel(id) {
  const m = MACHINES.find(x => x.id === id);
  if (!m) return id;
  const plate = m.plate ? m.plate + ' · ' : '';
  return plate + (typeof machineLabel === 'function' ? machineLabel(m) : m.name);
}

function AddRepairPage({ role = 'Operator', operatorName = 'Razak Hassan' }) {
  const isViewer = role !== 'Operator' && role !== 'Rigger' && role !== 'Admin';
  const todayISO = (typeof TODAY !== 'undefined' ? TODAY : new Date().toISOString().slice(0, 10));

  // Seed list — what this operator has reported recently, with workshop status.
  const [requests, setRequests] = React.useState([
    { id: 'RR-0231', machine: 'PLC-001', area: 'Hydraulics', severity: 'High',
      desc: 'Hydraulic oil leaking from boom cylinder when extending. Pressure drops.',
      date: (typeof addDaysISO === 'function' ? addDaysISO(todayISO, -1) : todayISO),
      status: 'In Workshop', photo: true, by: operatorName },
    { id: 'RR-0228', machine: 'PLC-001', area: 'Cabin / controls', severity: 'Low',
      desc: 'Aircon in cab not cold. Still drivable but hot in afternoon.',
      date: (typeof addDaysISO === 'function' ? addDaysISO(todayISO, -4) : todayISO),
      status: 'Reviewing', photo: false, by: operatorName },
  ]);

  // ---- Form state ----
  const [machine, setMachine] = React.useState('');
  const [area, setArea] = React.useState('');
  const [severity, setSeverity] = React.useState('Medium');
  const [desc, setDesc] = React.useState('');
  const [date, setDate] = React.useState(todayISO);
  const [photoName, setPhotoName] = React.useState('');
  const [photoUrl, setPhotoUrl] = React.useState('');
  const [showErrors, setShowErrors] = React.useState(false);
  const [toast, setToast] = React.useState(null);

  const errors = { machine: !machine, area: !area, desc: !desc.trim() };
  const hasErrors = Object.values(errors).some(Boolean);

  const resetForm = () => {
    setMachine(''); setArea(''); setSeverity('Medium'); setDesc('');
    setDate(todayISO); setPhotoName(''); setPhotoUrl(''); setShowErrors(false);
  };

  const onPickPhoto = (e) => {
    const f = e.target.files && e.target.files[0];
    if (!f) return;
    setPhotoName(f.name);
    try { setPhotoUrl(URL.createObjectURL(f)); } catch (_) {}
  };

  const submit = () => {
    if (hasErrors) { setShowErrors(true); return; }
    const seq = 232 + requests.filter(r => r.id.startsWith('RR-')).length;
    const newReq = {
      id: 'RR-0' + seq, machine, area, severity, desc: desc.trim(),
      date, status: 'Submitted', photo: !!photoName, by: operatorName,
    };
    setRequests([newReq, ...requests]);
    setToast('Repair reported · workshop notified');
    window.setTimeout(() => setToast(null), 2600);
    resetForm();
  };

  // ---- shared field primitives (mirrors the R&M form chrome) ----
  const labelStyle = { display: 'block', fontSize: 13, color: 'var(--color-grey-700)', marginBottom: 6, fontWeight: 600 };
  const reqStar = <span style={{color: '#d97706', marginLeft: 2, fontWeight: 700}}>*</span>;
  const inputBase = {
    width: '100%', height: 46, padding: '0 14px',
    border: '1px solid var(--color-grey-300)', borderRadius: 10,
    fontSize: 15, color: 'var(--color-grey-900, #111827)',
    background: 'white', boxSizing: 'border-box', fontFamily: 'inherit', outline: 'none',
  };
  const inputErr = { borderColor: '#dc2626', background: '#fef2f2' };

  const Field = ({ label, required, hint, error, children }) => (
    <div style={{marginBottom: 18}}>
      <label style={labelStyle}>{label}{required ? reqStar : null}</label>
      {children}
      {hint ? <div style={{fontSize: 12, color: 'var(--color-grey-500)', marginTop: 5}}>{hint}</div> : null}
      {error ? <div style={{fontSize: 12, color: '#dc2626', marginTop: 5, display: 'flex', alignItems: 'center', gap: 4}}><AlertTriangle size={12}/> {error}</div> : null}
    </div>
  );

  const statusPill = (s) => {
    const map = { 'Submitted': 'blue', 'Reviewing': 'orange', 'In Workshop': 'yellow', 'Done': 'green' };
    return <span className={"status status--" + (map[s] || 'gray')}>{s}</span>;
  };

  return (
    <div className="page">
      {/* Intro */}
      <div className="page-actions" style={{marginBottom: 18, alignItems: 'flex-end'}}>
        <div>
          <div className="eyebrow">Operator · Report a fault</div>
          <h2 style={{fontSize: 24, margin: '6px 0 0'}}>Add a Repair</h2>
          <div style={{fontSize: 13, color: 'var(--color-grey-600)', marginTop: 6, maxWidth: 520, lineHeight: 1.5}}>
            Found something wrong with your machine? Report it here and the workshop sees it straight away — no need to call.
          </div>
        </div>
      </div>

      <div className="addrepair-grid">
        {/* ---- Form card ---- */}
        {/* Backend:
            Form  -> form_add_repair
            Table -> repair_tickets (machine_id, issue, priority, photo_path, created_by)
            API   -> POST /api/repairs
            Perm  -> Operator(own), Rigger, Admin, Operation, Mechanic
            Validate -> machine_id, area(issue), desc required; photo image-mime + size cap
            Security -> auth; operator scoped to own machine; EXIF stripped; audit_log */}
        <div className="card" data-name="form_add_repair" data-map="POST /api/repairs" data-perm="Operator,Rigger,Admin,Operation,Mechanic">
          <div className="card__header">
            <div>
              <h3 className="card__title">What needs repair?</h3>
              <div className="card__sub">Fill the marked fields and submit</div>
            </div>
          </div>
          <div className="card__body" style={{padding: '20px 22px'}}>

            {/* Machine */}
            <Field label="My machine" required
              hint="The crane / lift you are running today."
              error={showErrors && errors.machine ? 'Pick your machine' : null}>
              <div style={{position: 'relative'}}>
                <select value={machine} name="machine_id" data-name="select_repair_machine" data-map="repair_tickets.machine_id" data-perm="Operator,Rigger,Admin,Operation,Mechanic" onChange={e => setMachine(e.target.value)}
                  style={{...inputBase, appearance: 'none', paddingRight: 44, color: machine ? 'inherit' : 'var(--color-grey-400)', ...(showErrors && errors.machine ? inputErr : {})}}>
                  <option value="">— Select your machine —</option>
                  {MACHINES.map(m => (
                    <option key={m.id} value={m.id}>{m.id} · {repairMachineLabel(m.id)}</option>
                  ))}
                </select>
                <ChevDown size={16} style={{position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)', pointerEvents: 'none'}}/>
              </div>
            </Field>

            {/* Problem area */}
            <Field label="Problem area" required
              error={showErrors && errors.area ? 'Pick what is wrong' : null}>
              <div style={{position: 'relative'}}>
                <select value={area} name="issue_area" data-name="select_repair_area" data-map="repair_tickets.issue" data-perm="Operator,Rigger,Admin,Operation,Mechanic" onChange={e => setArea(e.target.value)}
                  style={{...inputBase, appearance: 'none', paddingRight: 44, color: area ? 'inherit' : 'var(--color-grey-400)', ...(showErrors && errors.area ? inputErr : {})}}>
                  <option value="">— Select problem area —</option>
                  {REPAIR_AREAS.map(a => <option key={a} value={a}>{a}</option>)}
                </select>
                <ChevDown size={16} style={{position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)', pointerEvents: 'none'}}/>
              </div>
            </Field>

            {/* Severity — segmented */}
            <Field label="How bad is it?" required>
              <div className="sev-seg">
                {SEVERITY.map(s => {
                  const active = severity === s.id;
                  return (
                    <button key={s.id} type="button"
                      onClick={() => setSeverity(s.id)}
                      className={"sev-seg__btn " + (active ? "sev-seg__btn--active sev-seg__btn--" + s.id.toLowerCase() : "")}>
                      <span className="sev-seg__label">{s.label}</span>
                      <span className="sev-seg__note">{s.note}</span>
                    </button>
                  );
                })}
              </div>
            </Field>

            {/* Description */}
            <Field label="Describe the problem" required
              hint="What happens, when it started, any noise or warning light."
              error={showErrors && errors.desc ? 'Add a short description' : null}>
              <textarea value={desc} name="issue" data-name="input_repair_desc" data-map="repair_tickets.issue" data-perm="Operator,Rigger,Admin,Operation,Mechanic" onChange={e => setDesc(e.target.value)}
                placeholder="e.g. Boom is slow to lift and making a knocking sound when loaded…"
                style={{...inputBase, height: 'auto', minHeight: 96, padding: '12px 14px', resize: 'vertical', lineHeight: 1.45, ...(showErrors && errors.desc ? inputErr : {})}}/>
            </Field>

            {/* Photo */}
            <Field label="Photo" hint="Optional — a photo helps the mechanic prepare parts.">
              {photoUrl ? (
                <div style={{display: 'flex', alignItems: 'center', gap: 12, padding: 10, border: '1px solid var(--color-grey-200)', borderRadius: 10}}>
                  <img src={photoUrl} alt="" style={{width: 56, height: 56, objectFit: 'cover', borderRadius: 8, flexShrink: 0}}/>
                  <div style={{flex: 1, minWidth: 0}}>
                    <div style={{fontSize: 13, fontWeight: 600, color: 'var(--color-navy)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap'}}>{photoName}</div>
                    <div style={{fontSize: 12, color: 'var(--color-grey-500)'}}>Attached</div>
                  </div>
                  <button type="button" onClick={() => { setPhotoName(''); setPhotoUrl(''); }}
                    style={{background: 'var(--color-grey-100)', border: 'none', width: 30, height: 30, borderRadius: 7, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--color-grey-600)'}}>
                    <X size={15}/>
                  </button>
                </div>
              ) : (
                <label className="addrepair-photo">
                  <input type="file" name="photo" data-name="upload_repair_photo" data-map="repair_tickets.photo_path" data-perm="Operator,Rigger,Admin,Operation,Mechanic" accept="image/*" capture="environment" onChange={onPickPhoto} style={{display: 'none'}}/>
                  <Camera size={20}/>
                  <span>Take or upload a photo</span>
                </label>
              )}
            </Field>

            {/* Date noticed */}
            <Field label="Date noticed">
              <div style={{position: 'relative'}}>
                <input type="date" value={date} onChange={e => setDate(e.target.value)}
                  style={{...inputBase, paddingRight: 44}}/>
                <Calendar size={18} style={{position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)', color: 'var(--color-grey-500)', pointerEvents: 'none'}}/>
              </div>
            </Field>

            {showErrors && hasErrors ? (
              <div style={{padding: 12, background: '#fef2f2', border: '1px solid #fecaca', borderLeft: '4px solid #dc2626', borderRadius: 8, color: '#991b1b', fontSize: 13, display: 'flex', alignItems: 'flex-start', gap: 8, marginBottom: 16}}>
                <AlertTriangle size={16} style={{flexShrink: 0, marginTop: 1}}/>
                <div><strong>Almost there.</strong> Fill the fields marked <span style={{color: '#d97706', fontWeight: 700}}>*</span> before sending.</div>
              </div>
            ) : null}

            <div style={{display: 'flex', gap: 10}}>
              <button type="button" className="btn btn--primary" data-name="btn_submit_repair" data-map="POST /api/repairs" data-perm="Operator,Rigger,Admin,Operation,Mechanic" style={{flex: 1, height: 48, justifyContent: 'center', fontSize: 15}} onClick={submit}>
                <Wrench size={16}/> Submit Repair
              </button>
              <button type="button" className="btn btn--ghost" style={{height: 48}} onClick={resetForm}>Clear</button>
            </div>
          </div>
        </div>

        {/* ---- My requests ---- */}
        <div className="card" style={{alignSelf: 'flex-start'}}>
          <div className="card__header">
            <div>
              <h3 className="card__title">My repair reports</h3>
              <div className="card__sub">Latest first · workshop status</div>
            </div>
            <span className="status status--gray">{requests.length}</span>
          </div>
          <div className="card__body" style={{padding: 0}}>
            {requests.map(r => (
              <div key={r.id} style={{padding: '14px 18px', borderBottom: '1px solid var(--color-grey-100)'}}>
                <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8}}>
                  <div style={{flex: 1, minWidth: 0}}>
                    <div style={{display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap'}}>
                      <span style={{fontFamily: 'monospace', fontSize: 11, color: 'var(--color-grey-500)'}}>{r.id}</span>
                      <span className={"status status--" + severityStatus(r.severity)}>{r.severity}</span>
                      {r.photo ? <Camera size={13} style={{color: 'var(--color-grey-400)'}}/> : null}
                    </div>
                    <div style={{fontWeight: 600, fontSize: 14, color: 'var(--color-navy)', marginTop: 4}}>
                      {repairMachineLabel(r.machine)}
                    </div>
                    <div style={{fontSize: 13, color: 'var(--color-grey-700)', marginTop: 2}}>{r.area}</div>
                    <div style={{fontSize: 12.5, color: 'var(--color-grey-600)', marginTop: 4, lineHeight: 1.4}}>{r.desc}</div>
                    <div style={{fontSize: 11, color: 'var(--color-grey-500)', marginTop: 6}}>
                      Reported {new Date(r.date + 'T00:00:00').toLocaleDateString('en-GB', { day: '2-digit', month: 'short' })} · {r.by}
                    </div>
                  </div>
                  <div style={{flexShrink: 0}}>{statusPill(r.status)}</div>
                </div>
              </div>
            ))}
            {requests.length === 0 ? (
              <div style={{padding: 28, textAlign: 'center', color: 'var(--color-grey-500)', fontSize: 14}}>No repairs reported yet.</div>
            ) : null}
          </div>
        </div>
      </div>

      {/* Toast */}
      {toast ? (
        <div style={{
          position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)',
          background: 'var(--color-navy)', color: 'white', padding: '12px 20px',
          borderRadius: 10, display: 'flex', alignItems: 'center', gap: 10,
          boxShadow: '0 12px 30px rgba(11,31,58,0.35)', zIndex: 1200, fontSize: 14, fontWeight: 600,
        }}>
          <Check size={16}/> {toast}
        </div>
      ) : null}
    </div>
  );
}

Object.assign(window, { AddRepairPage });

// Backend metadata (see docs/BACKEND_MAPPING.md)
AddRepairPage.meta = {
  devName: 'form_add_repair',
  purpose: 'Operator/Rigger reports a machine fault to the workshop',
  table: 'repair_tickets',
  api: { create: 'POST /api/repairs', list: 'GET /api/repairs?mine=1' },
  permission: ['Operator', 'Rigger', 'Admin', 'Operation', 'Mechanic'],
  notes: 'Severity => repair_tickets.priority. Photo stored as file (photo_path), '
       + 'image-mime + size validated, EXIF stripped. Operator sees only own reports.'
};
