// 05 Workflows (page-spec.md): request types (3) + vertical steps (9). Advanced view = the old canvas.
import { useState } from 'react';
import { WorkflowView } from '../PlaceholderViews';
import { Page, Card, Segmented, useToast, useRights } from './ui';

const TYPES = {
  claims: { name: 'Claims', steps: [
    { title: 'Claim sent', approver: 'Staff member', upTo: '', ifDeclined: 'Back to the staff member' },
    { title: 'Manager check', approver: 'Team Lead (branch) or HR (HQ)', upTo: '500', ifDeclined: 'Back to the staff member' },
    { title: 'Finance approval', approver: 'Finance', upTo: '500', ifDeclined: 'Back to the manager' },
    { title: 'Mark as paid', approver: 'Finance', upTo: '', ifDeclined: 'Stays approved' }] },
  spend: { name: 'Spend requests', steps: [
    { title: 'Request sent', approver: 'Staff member', upTo: '', ifDeclined: 'Back to the requester' },
    { title: 'Finance approval', approver: 'Finance', upTo: '500', ifDeclined: 'Back to the requester' },
    { title: 'HQ approval (over RM 500)', approver: 'Director or Operations Lead', upTo: '100000', ifDeclined: 'Back to the requester' }] },
  leave: { name: 'Leave', steps: [
    { title: 'Leave request sent', approver: 'Staff member', upTo: '', ifDeclined: 'Back to the staff member' },
    { title: 'Manager approval', approver: 'Team Lead', upTo: '', ifDeclined: 'Back to the staff member' },
    { title: 'HR records it', approver: 'HR', upTo: '', ifDeclined: 'Back to the manager' }] },
  leads: { name: 'Leads', steps: [
    { title: 'Enquiry received', approver: 'Business Development', upTo: '', ifDeclined: 'Closed as lost' },
    { title: 'Check the lead', approver: 'Business Development', upTo: '', ifDeclined: 'On hold: can\'t contact customer' },
    { title: 'Prepare quote', approver: 'Business Development', upTo: '', ifDeclined: 'On hold: can\'t contact customer' },
    { title: 'On hold: can\'t contact customer', approver: 'Team Lead', upTo: '', ifDeclined: 'Closed as lost' },
    { title: 'Manager approval', approver: 'Team Lead', upTo: '5000', ifDeclined: 'Back to Prepare quote' }] } };

export default function WorkflowsPage() {
  const toast = useToast();
  const [mode, setMode] = useState('steps');
  const canEdit = useRights('workflow', '').edit; // Operations Lead only
  const [type, setType] = useState('leads');
  const [flows, setFlows] = useState(TYPES);
  const [dirty, setDirty] = useState(false);
  const [saved, setSaved] = useState(null); // inline 'Saved' note, fades after 2s (no pop-up)
  const flashSaved = () => { setSaved('show'); setTimeout(() => setSaved('fade'), 1600); setTimeout(() => setSaved(null), 2000); };
  const steps = flows[type].steps;
  const edit = (i, k, v) => { setFlows(f => ({ ...f, [type]: { ...f[type], steps: f[type].steps.map((s, j) => j === i ? { ...s, [k]: v } : s) } })); setDirty(true); };
  const add = i => { setFlows(f => ({ ...f, [type]: { ...f[type], steps: [...f[type].steps.slice(0, i + 1), { title: 'New step', approver: '', upTo: '', ifDeclined: 'Back to the previous step' }, ...f[type].steps.slice(i + 1)] } })); setDirty(true); };
  return <Page title="Workflows" more={[{ label: 'Restore last saved', hidden: !dirty, onClick: () => { setFlows(TYPES); setDirty(false); } }]}
    secondary={<Segmented label="View" options={[['steps', 'Steps'], ['advanced', 'Advanced view']]} value={mode} onChange={setMode} />}
    primary={canEdit && <span style={{ display: 'inline-flex', alignItems: 'center', gap: 12 }}>{saved && <span className={`sp-saved${saved === 'fade' ? ' fade' : ''}`} role="status">Saved</span>}<button type="button" className="sp-btn primary" disabled={!dirty} onClick={() => { setDirty(false); flashSaved(); }}>Save</button></span>}
    footnote="Demo only. Saving here doesn't change how requests are approved yet.">
    {mode === 'advanced' ? <WorkflowView /> : <div className="sp-grid">
      <Card className="sp-span-3" title="Request types" flush><ul style={{ listStyle: 'none', margin: 0, padding: 8 }}>{Object.entries(flows).map(([k, f]) =>
        <li key={k}><button type="button" aria-pressed={type === k} onClick={() => setType(k)} style={{ display: 'flex', justifyContent: 'space-between', width: '100%', padding: '10px 12px', border: 0, borderRadius: 8, cursor: 'pointer', fontFamily: 'inherit', fontSize: 14, background: type === k ? 'var(--c-accent-soft)' : 'transparent', color: type === k ? 'var(--c-accent-text)' : 'var(--c-text)', fontWeight: type === k ? 600 : 400 }}>
          <span>{f.name}</span><span className="sp-muted">{f.steps.length} steps</span></button></li>)}</ul></Card>
      <Card className="sp-span-9" title={`${flows[type].name}`} meta={`${steps.length} steps${dirty ? ' · Not saved' : ''}`}>
        <ol className={canEdit ? '' : 'sp-ro'} style={{ listStyle: 'none', margin: 0, padding: 0 }}>{steps.map((s, i) => <li key={i}>
          <div style={{ display: 'grid', gridTemplateColumns: '32px minmax(0,1fr)', gap: 12 }}>
            <span style={{ width: 28, height: 28, borderRadius: '50%', background: '#E8F4FB', color: '#0077B3', fontWeight: 700, fontSize: 13, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>{i + 1}</span>
            <div style={{ border: '1px solid var(--c-border)', borderRadius: 10, padding: 14 }}>
              <input aria-label={`Step ${i + 1} name`} value={s.title} readOnly={!canEdit} onChange={e => edit(i, 'title', e.target.value)} style={{ border: 0, fontFamily: 'inherit', fontSize: 15, fontWeight: 600, width: '100%', background: 'transparent', color: 'var(--c-text)', padding: 0, marginBottom: 10 }} />
              <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 2fr', gap: 12 }}>
                <label className="sp-field" style={{ marginBottom: 0 }}><span>Approver</span><input value={s.approver} readOnly={!canEdit} onChange={e => edit(i, 'approver', e.target.value)} /></label>
                <label className="sp-field" style={{ marginBottom: 0 }}><span>Up to (RM)</span><input inputMode="numeric" value={s.upTo} readOnly={!canEdit} placeholder="No limit" onChange={e => edit(i, 'upTo', e.target.value.replace(/[^0-9]/g, ''))} /></label>
                <label className="sp-field" style={{ marginBottom: 0 }}><span>If declined</span><input value={s.ifDeclined} readOnly={!canEdit} onChange={e => edit(i, 'ifDeclined', e.target.value)} /></label>
              </div>
              {i < steps.length - 1 && <div className="sp-muted" style={{ fontSize: 12, marginTop: 8 }}>1 next step</div>}
            </div>
          </div>
          {canEdit ? <div style={{ display: 'flex', justifyContent: 'center', padding: '6px 0 6px 44px' }}><button type="button" className="sp-btn link" style={{ height: 28, fontSize: 13 }} onClick={() => add(i)}>+ Add step</button></div> : <div style={{ height: 12 }} />}
        </li>)}</ol>
      </Card></div>}
  </Page>;
}
