// Edit-case modal — lets the doctor correct patient_id / patient_name /
// cancer_type / stage when the OCR got something wrong, without forcing a
// re-upload. Backend treats blank strings as "leave alone" so partial edits
// can't accidentally erase data.
const EditCaseModal = ({ row, onClose, onSaved }) => {
  const t = window.useLanguage().t;
  const [patientId,   setPatientId]   = React.useState(row?.id   === 'Unnamed' ? '' : (row?.id   || ''));
  const [patientName, setPatientName] = React.useState(row?.name === 'Unnamed' ? '' : (row?.name || ''));
  const [cancerType,  setCancerType]  = React.useState(row?.dx    || '');
  const [stage,       setStage]       = React.useState(row?.stage || '');
  const [stage_, setStage_] = React.useState({saving:false, err:''});

  const save = async () => {
    if (!row?._caseId) return;
    setStage_({saving:true, err:''});
    const patch = {};
    // Only send fields that actually changed AND are non-empty. Backend
    // strips empty strings either way, but skipping them client-side
    // keeps the request body honest.
    if (patientId.trim()   && patientId.trim()   !== (row.id   === 'Unnamed' ? '' : row.id))   patch.patient_id   = patientId.trim();
    if (patientName.trim() && patientName.trim() !== (row.name === 'Unnamed' ? '' : row.name)) patch.patient_name = patientName.trim();
    if (cancerType.trim()  && cancerType.trim()  !== (row.dx    || ''))                         patch.cancer_type  = cancerType.trim();
    if (stage.trim()       && stage.trim()       !== (row.stage || ''))                         patch.stage        = stage.trim();
    if (Object.keys(patch).length === 0) { onClose(); return; }
    try {
      await window.AicanAPI.editCase(row._caseId, patch);
      setStage_({saving:false, err:''});
      onSaved && onSaved();
    } catch (e) {
      setStage_({saving:false, err: e.message || 'Edit failed'});
    }
  };

  return (
    <div className="modal-scrim" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:8}}>
          <div>
            <h2>{t('Edit case')}</h2>
            <p>{t('Correct any field the OCR misread. Blank fields are left unchanged.')}</p>
          </div>
          <div onClick={onClose} style={{cursor:'pointer', color:'var(--fg-3)'}}><IconClose size={18}/></div>
        </div>

        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:8, marginBottom:10}}>
          <input className="ti" placeholder={t('Patient ID')}
            value={patientId} onChange={e=>setPatientId(e.target.value)}/>
          <input className="ti" placeholder={t('Patient name')}
            value={patientName} onChange={e=>setPatientName(e.target.value)}/>
        </div>
        <div style={{display:'grid', gridTemplateColumns:'2fr 1fr', gap:8, marginBottom:10}}>
          <input className="ti" placeholder={t('Diagnosis / cancer type')}
            value={cancerType} onChange={e=>setCancerType(e.target.value)}/>
          <input className="ti" placeholder={t('Stage')}
            value={stage} onChange={e=>setStage(e.target.value)}/>
        </div>

        {stage_.err && (
          <div style={{marginTop:4, padding:'8px 10px', fontSize:16, borderRadius:6,
            background:'rgba(220,38,38,0.08)', color:'#b91c1c'}}>{stage_.err}</div>
        )}

        <div className="actions">
          <button className="btn ghost" onClick={onClose} disabled={stage_.saving}>{t('Cancel')}</button>
          <button className="btn primary" onClick={save} disabled={stage_.saving}>
            {stage_.saving ? t('Working…') : t('Save changes')}
          </button>
        </div>
      </div>
    </div>
  );
};

window.EditCaseModal = EditCaseModal;
