// Form Builder — drag fields onto a canvas
const FIELD_TYPES = [
  { type: 'text', label: 'Text', icon: 'form', desc: 'Single-line text input' },
  { type: 'textarea', label: 'Long text', icon: 'list', desc: 'Multi-line text area' },
  { type: 'number', label: 'Number', icon: 'chart', desc: 'Numeric value with units' },
  { type: 'select', label: 'Dropdown', icon: 'chevronDown', desc: 'Single-choice select' },
  { type: 'radio', label: 'Single choice', icon: 'check', desc: 'Radio buttons' },
  { type: 'check', label: 'Checklist', icon: 'check', desc: 'Pass/fail checklist' },
  { type: 'photo', label: 'Photo', icon: 'eye', desc: 'Camera capture' },
  { type: 'sig', label: 'Signature', icon: 'edit', desc: 'Operator signature' },
  { type: 'machine', label: 'Machine picker', icon: 'cpu', desc: 'Select a machine' },
  { type: 'lot', label: 'Lot / batch', icon: 'database', desc: 'Lot or batch reference' },
  { type: 'reading', label: 'Sensor reading', icon: 'thermometer', desc: 'Auto-pull from sensor' },
  { type: 'scan', label: 'Scan barcode', icon: 'grid', desc: 'Barcode/QR scan' },
];

const initialFormFields = [
  { id: 'f1', type: 'machine', label: 'Machine', required: true, value: 'CNC-04' },
  { id: 'f2', type: 'lot', label: 'Lot number', required: true, placeholder: 'Scan or enter' },
  { id: 'f3', type: 'select', label: 'Inspection type', required: true, options: ['Incoming', 'In-process', 'Final'] },
  { id: 'f4', type: 'reading', label: 'Spindle temp (°C)', sensor: 'TC-04', readonly: true },
  { id: 'f5', type: 'number', label: 'Diameter measurement (mm)', required: true, unit: 'mm', tolerance: '12.50 ± 0.05' },
  { id: 'f6', type: 'check', label: 'Visual inspection', items: ['Surface finish OK', 'No burrs', 'Dimensions within spec', 'Marking legible'] },
  { id: 'f7', type: 'photo', label: 'Defect photo (if any)', optional: true },
  { id: 'f8', type: 'textarea', label: 'Notes', placeholder: 'Operator observations' },
  { id: 'f9', type: 'sig', label: 'Inspector signature', required: true },
];

const FormsPage = () => {
  const [tab, setTab] = useState('builder');
  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Forms</h1>
          <div className="page-sub">28 published forms · 4 drafts · QA Inspection v4 — last edited 2h ago</div>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="copy" size={12}/>Templates</button>
          <button className="btn"><Icon name="eye" size={12}/>Preview</button>
          <button className="btn primary"><Icon name="check" size={12}/>Publish</button>
        </div>
      </div>

      <div className="tabs">
        <div className={`tab ${tab==='builder'?'active':''}`} onClick={()=>setTab('builder')}>Builder</div>
        <div className={`tab ${tab==='subs'?'active':''}`} onClick={()=>setTab('subs')}>Submissions <span className="count">312</span></div>
        <div className={`tab ${tab==='all'?'active':''}`} onClick={()=>setTab('all')}>All forms <span className="count">28</span></div>
        <div className={`tab ${tab==='logic'?'active':''}`} onClick={()=>setTab('logic')}>Logic & validation</div>
      </div>

      {tab === 'builder' && <FormBuilder/>}
      {tab === 'subs' && <FormSubmissions/>}
      {tab === 'all' && <AllForms/>}
      {tab === 'logic' && <LogicView/>}
    </>
  );
};

const FormBuilder = () => {
  const [fields, setFields] = useState(initialFormFields);
  const [selected, setSelected] = useState('f5');
  const [dragOver, setDragOver] = useState(null);
  const [dragField, setDragField] = useState(null);
  const toast = useToast();

  const addField = (type) => {
    const id = 'f' + (fields.length + 100);
    const t = FIELD_TYPES.find(x => x.type === type);
    setFields(f => [...f, { id, type, label: t.label, required: false }]);
    setSelected(id);
    toast.push(`Added "${t.label}" field`);
  };

  const moveField = (fromId, toId) => {
    if (fromId === toId) return;
    setFields(fs => {
      const fromIdx = fs.findIndex(f => f.id === fromId);
      const toIdx = fs.findIndex(f => f.id === toId);
      const next = [...fs];
      const [moved] = next.splice(fromIdx, 1);
      next.splice(toIdx, 0, moved);
      return next;
    });
  };

  const sel = fields.find(f => f.id === selected);

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '240px 1fr 320px', height: 'calc(100vh - 44px - 91px - 40px)' }}>
      {/* Field palette */}
      <div style={{ borderRight: '1px solid var(--line)', background: 'var(--panel)', overflowY: 'auto', padding: '14px 12px' }}>
        <div style={{ fontSize: 12, fontWeight: 500, marginBottom: 4 }}>QA Inspection v4</div>
        <div className="mono" style={{ fontSize: 10.5, color: 'var(--text-3)', marginBottom: 14 }}>id: form_qa_insp_v4</div>

        <div className="sec-heading">Field types</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {FIELD_TYPES.map(f => (
            <div key={f.type} onClick={() => addField(f.type)}
              style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '7px 8px', borderRadius: 4, cursor: 'pointer' }}
              onMouseEnter={e => e.currentTarget.style.background = 'var(--panel-2)'}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <div style={{ width: 22, height: 22, borderRadius: 3, background: 'var(--panel-2)', color: 'var(--text-2)', display: 'grid', placeItems: 'center', flex: '0 0 22px' }}>
                <Icon name={f.icon} size={12}/>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12, fontWeight: 500 }}>{f.label}</div>
                <div style={{ fontSize: 10, color: 'var(--text-3)' }}>{f.desc}</div>
              </div>
              <Icon name="plus" size={11} style={{ color: 'var(--text-4)' }}/>
            </div>
          ))}
        </div>
      </div>

      {/* Canvas — form preview */}
      <div style={{ overflow: 'auto', padding: '24px 32px', background: 'var(--bg)' }}>
        <div style={{ maxWidth: 580, margin: '0 auto' }}>
          <div className="card" style={{ marginBottom: 16 }}>
            <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--line)' }}>
              <div style={{ fontSize: 15, fontWeight: 600 }}>QA Inspection — In-process</div>
              <div style={{ fontSize: 11.5, color: 'var(--text-3)', marginTop: 3 }}>
                For dimensional checks during machining cycles. Triggers CAPA workflow on out-of-spec.
              </div>
            </div>
            <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 14 }}>
              {fields.map((f, idx) => (
                <FieldRender key={f.id} field={f} selected={selected === f.id}
                  onSelect={() => setSelected(f.id)}
                  onDragStart={() => setDragField(f.id)}
                  onDragOver={(e) => { e.preventDefault(); setDragOver(f.id); }}
                  onDrop={() => { if (dragField) moveField(dragField, f.id); setDragField(null); setDragOver(null); }}
                  isDragOver={dragOver === f.id && dragField !== f.id}/>
              ))}
              <div onClick={() => addField('text')}
                style={{ border: '1.5px dashed var(--line-2)', borderRadius: 5, padding: '14px', textAlign: 'center', color: 'var(--text-3)', fontSize: 12, cursor: 'pointer' }}>
                <Icon name="plus" size={12} style={{ marginRight: 6, verticalAlign: 'middle' }}/>
                Add field — or drag from the left panel
              </div>
            </div>
          </div>

          <div style={{ display: 'flex', gap: 8, fontSize: 11, color: 'var(--text-3)' }} className="mono">
            <span>{fields.length} fields</span>
            <span>·</span>
            <span>{fields.filter(f=>f.required).length} required</span>
            <span>·</span>
            <span>3 validation rules</span>
            <span>·</span>
            <span>links to: workflow "QA failure routing"</span>
          </div>
        </div>
      </div>

      {/* Field config */}
      <div style={{ borderLeft: '1px solid var(--line)', background: 'var(--panel)', overflowY: 'auto' }}>
        {sel ? <FieldConfig field={sel}/> : <div style={{ padding: 20, color: 'var(--text-3)', fontSize: 12 }}>Select a field to configure</div>}
      </div>
    </div>
  );
};

const FieldRender = ({ field, selected, onSelect, onDragStart, onDragOver, onDrop, isDragOver }) => {
  const containerStyle = {
    border: `1.5px solid ${selected ? 'var(--accent)' : isDragOver ? 'var(--blue)' : 'transparent'}`,
    borderRadius: 5,
    padding: 8,
    margin: '-8px',
    cursor: 'pointer',
    position: 'relative',
    background: isDragOver ? 'color-mix(in srgb, var(--blue) 6%, transparent)' : selected ? 'color-mix(in srgb, var(--accent) 4%, transparent)' : 'transparent',
  };

  return (
    <div style={containerStyle} onClick={onSelect}
      draggable onDragStart={onDragStart} onDragOver={onDragOver} onDrop={onDrop}>
      <div style={{ position: 'absolute', left: -22, top: '50%', transform: 'translateY(-50%)', color: 'var(--text-4)', display: selected ? 'block' : 'none' }}>
        <Icon name="drag" size={12}/>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, fontWeight: 500, marginBottom: 6 }}>
        {field.label}
        {field.required && <span style={{ color: 'var(--red)' }}>*</span>}
        {field.readonly && <span className="pill" style={{ fontSize: 9 }}>auto</span>}
      </div>
      <FieldInputPreview field={field}/>
      {field.tolerance && <div className="mono" style={{ fontSize: 10.5, color: 'var(--text-3)', marginTop: 4 }}>tolerance: {field.tolerance}</div>}
    </div>
  );
};

const FieldInputPreview = ({ field }) => {
  const baseInput = { width: '100%', height: 30, padding: '0 10px', border: '1px solid var(--line)', borderRadius: 4, background: 'var(--panel-2)', fontSize: 12, color: 'var(--text-3)' };
  switch (field.type) {
    case 'text':
    case 'lot':
      return <div style={baseInput}>{field.placeholder || `Enter ${field.label.toLowerCase()}…`}</div>;
    case 'number':
      return (
        <div style={{ display: 'flex', gap: 6 }}>
          <div style={{ ...baseInput, flex: 1 }}>0.00</div>
          {field.unit && <div style={{ ...baseInput, width: 50, textAlign: 'center', fontFamily: 'JetBrains Mono' }}>{field.unit}</div>}
        </div>
      );
    case 'textarea':
      return <div style={{ ...baseInput, height: 60, padding: 10, lineHeight: 1.4 }}>{field.placeholder || 'Type here…'}</div>;
    case 'select':
      return (
        <div style={{ ...baseInput, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span>{field.options?.[0] || 'Select…'}</span>
          <Icon name="chevronDown" size={11}/>
        </div>
      );
    case 'check':
      return (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
          {field.items?.map((it, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
              <div style={{ width: 14, height: 14, border: '1.5px solid var(--line-2)', borderRadius: 3 }}/>
              <span style={{ color: 'var(--text-2)' }}>{it}</span>
            </div>
          ))}
        </div>
      );
    case 'photo':
      return <div style={{ height: 80, border: '1.5px dashed var(--line-2)', borderRadius: 4, display: 'grid', placeItems: 'center', color: 'var(--text-3)', fontSize: 11.5 }}><Icon name="eye" size={16}/></div>;
    case 'sig':
      return <div style={{ height: 60, border: '1.5px dashed var(--line-2)', borderRadius: 4, display: 'grid', placeItems: 'center', color: 'var(--text-3)', fontSize: 11.5 }}>Sign here</div>;
    case 'machine':
      return (
        <div style={{ ...baseInput, display: 'flex', alignItems: 'center', gap: 8 }}>
          <Icon name="cpu" size={11}/>
          <span className="mono" style={{ color: 'var(--text)' }}>{field.value || 'Select machine'}</span>
        </div>
      );
    case 'reading':
      return (
        <div style={{ ...baseInput, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span className="mono" style={{ color: 'var(--text)' }}>87.3 °C</span>
          <span style={{ fontSize: 10, color: 'var(--text-3)', fontFamily: 'JetBrains Mono' }}>← {field.sensor}</span>
        </div>
      );
    case 'scan':
      return <div style={{ ...baseInput, display: 'flex', alignItems: 'center', gap: 8 }}><Icon name="grid" size={11}/><span>Tap to scan</span></div>;
    case 'radio':
      return <div style={{ display: 'flex', gap: 12, fontSize: 12 }}>{['Pass','Fail','Hold'].map(o => <span key={o} style={{ display: 'flex', alignItems: 'center', gap: 5, color: 'var(--text-2)' }}><span style={{ width: 12, height: 12, borderRadius: '50%', border: '1.5px solid var(--line-2)' }}/>{o}</span>)}</div>;
    default:
      return <div style={baseInput}/>;
  }
};

const FieldConfig = ({ field }) => (
  <div>
    <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--line)' }}>
      <div className="mono" style={{ fontSize: 10.5, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--accent)' }}>Field · {field.type}</div>
      <div style={{ fontSize: 14, fontWeight: 500, marginTop: 4 }}>{field.label}</div>
    </div>
    <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 14 }}>
      <Field label="Field label" value={field.label}/>
      <Field label="Field key" value={`field_${field.id}`} mono/>
      <Field label="Help text" value="Shown below the input on the form"/>

      <div className="sec-heading" style={{ marginTop: 4 }}>Validation</div>
      <ToggleRow label="Required" on={field.required}/>
      <ToggleRow label="Show on mobile only" on={false}/>
      {field.type === 'number' && (
        <>
          <Field label="Unit" value={field.unit || ''}/>
          <Field label="Min / Max" value="12.45 / 12.55" mono/>
          <Field label="Out-of-spec rule" value="Trigger CAPA workflow"/>
        </>
      )}

      <div className="sec-heading" style={{ marginTop: 4 }}>Logic</div>
      <Field label="Show this field if" value="inspection_type ≠ 'Incoming'" mono/>
      <Field label="On change" value="Update lot record"/>

      <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
        <button className="btn primary sm" style={{ flex: 1 }}>Save</button>
        <button className="btn sm icon"><Icon name="copy" size={12}/></button>
        <button className="btn sm icon" style={{ color: 'var(--red)' }}><Icon name="trash" size={12}/></button>
      </div>
    </div>
  </div>
);

const ToggleRow = ({ label, on }) => {
  const [v, setV] = useState(on);
  return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '4px 0' }}>
      <span style={{ fontSize: 12 }}>{label}</span>
      <div className={`switch ${v ? 'on' : ''}`} onClick={() => setV(!v)}/>
    </div>
  );
};

const FormSubmissions = () => (
  <div className="page-body">
    <div className="card">
      <table className="tbl">
        <thead><tr><th>Submission</th><th>Form</th><th>Operator</th><th>Machine</th><th>Result</th><th>Submitted</th><th></th></tr></thead>
        <tbody>
          {[
            ['SUB-08471','QA Inspection v4','S. Joshi','CNC-04','fail','14:31'],
            ['SUB-08470','Maintenance log','A. Desai','PRESS-12','pass','14:18'],
            ['SUB-08469','QA Inspection v4','R. Mehta','CNC-02','pass','14:11'],
            ['SUB-08468','Shift report','P. Kulkarni','—','pass','14:00'],
            ['SUB-08467','Incoming inspection','S. Joshi','—','pass','13:42'],
            ['SUB-08466','QA Inspection v4','R. Mehta','ASM-02','hold','13:14'],
            ['SUB-08465','Tool change log','A. Desai','CNC-01','pass','12:48'],
          ].map((r,i) => (
            <tr key={i}>
              <td className="mono" style={{fontSize:11.5}}>{r[0]}</td>
              <td>{r[1]}</td>
              <td>{r[2]}</td>
              <td className="mono">{r[3]}</td>
              <td>
                <span className="pill" style={{ background: r[4]==='pass'?'color-mix(in srgb, var(--green) 12%, transparent)':r[4]==='fail'?'color-mix(in srgb, var(--red) 12%, transparent)':'color-mix(in srgb, var(--accent) 12%, transparent)', color: r[4]==='pass'?'var(--green)':r[4]==='fail'?'var(--red)':'var(--accent)' }}>
                  <span className="dot"/>{r[4]}
                </span>
              </td>
              <td className="mono" style={{fontSize:11.5}}>{r[5]}</td>
              <td><button className="btn ghost icon sm"><Icon name="eye" size={12}/></button></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  </div>
);

const AllForms = () => (
  <div className="page-body">
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
      {[
        ['QA Inspection','In-process · 9 fields','312 sub/wk','Quality','Active'],
        ['Maintenance log','Service record · 12 fields','148 sub/wk','Maintenance','Active'],
        ['Shift report','End of shift · 14 fields','21 sub/wk','Operations','Active'],
        ['Incoming inspection','Receiving · 8 fields','64 sub/wk','Quality','Active'],
        ['CAPA report','Corrective action · 16 fields','12 sub/wk','Quality','Active'],
        ['Tool change log','Tooling · 6 fields','94 sub/wk','Maintenance','Active'],
        ['Safety audit','Plant audit · 22 fields','4 sub/wk','EHS','Active'],
        ['Energy reading','Manual reading · 4 fields','—','Energy','Draft'],
        ['Approval — overtime','Approval · 5 fields','18 sub/wk','HR','Active'],
      ].map((f,i)=>(
        <div key={i} className="card">
          <div className="card-header">
            <div className="card-title">{f[0]}</div>
            <span className="pill" style={{ marginLeft: 'auto', color: f[4]==='Active'?'var(--green)':'var(--text-3)' }}>{f[4]}</span>
          </div>
          <div style={{ padding: 14 }}>
            <div className="mono" style={{ fontSize: 11, color: 'var(--text-2)' }}>{f[1]}</div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 12, fontSize: 11, color: 'var(--text-3)' }}>
              <span>{f[2]}</span><span>module · {f[3]}</span>
            </div>
          </div>
        </div>
      ))}
    </div>
  </div>
);

const LogicView = () => (
  <div className="page-body">
    <div className="card">
      <div className="card-header"><div className="card-title">Validation rules — QA Inspection v4</div></div>
      <div style={{ padding: 14, display: 'flex', flexDirection: 'column', gap: 8 }}>
        {[
          ['Diameter measurement', 'must be between 12.45 and 12.55 mm', 'fail → CAPA workflow'],
          ['Visual inspection', 'all 4 items must be checked', 'fail → hold lot'],
          ['Defect photo', 'required if any visual check is unticked', 'enforce client-side'],
        ].map((r,i)=>(
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', background: 'var(--panel-2)', border: '1px solid var(--line)', borderRadius: 4 }}>
            <span className="pill warn">rule {i+1}</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12, fontWeight: 500 }}>{r[0]}</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--text-2)', marginTop: 2 }}>{r[1]}</div>
            </div>
            <span className="mono" style={{ fontSize: 11, color: 'var(--text-3)' }}>{r[2]}</span>
          </div>
        ))}
      </div>
    </div>
  </div>
);

window.FormsPage = FormsPage;
