/* eslint-disable */
/* =========================================================
   TEO IoT Dashboard — Reports.
   Two surfaces: scheduled reports (recurring) and library
   (templates that can be run ad-hoc or scheduled).
   ========================================================= */

const SCHEDULED = [
  { id:'RPT-001', name:'Daily operations rollup',         schedule:'Daily · 00:05',     recipients:['ops@teo','tom@ng'], lastRun:'12 May 00:05', state:'enabled',  format:'PDF', size:'1.8 MB' },
  { id:'RPT-002', name:'Weekly mesh health summary',      schedule:'Mon · 07:00',       recipients:['mesh@teo'],         lastRun:'12 May 07:00', state:'enabled',  format:'PDF', size:'820 KB' },
  { id:'RPT-003', name:'Monthly compliance · 2026-04',    schedule:'1st · 06:00',       recipients:['compliance@ng'],    lastRun:'01 May 06:00', state:'enabled',  format:'PDF', size:'4.2 MB' },
  { id:'RPT-004', name:'Battery cycle audit · NG-LDN-01', schedule:'Weekly · Fri 18:00',recipients:['energy@teo'],       lastRun:'09 May 18:00', state:'paused',   format:'CSV', size:'214 KB' },
  { id:'RPT-005', name:'AGV utilisation · BHX-04',        schedule:'Daily · 22:00',     recipients:['logistics@teo'],    lastRun:'11 May 22:00', state:'enabled',  format:'XLSX',size:'430 KB' },
];

const LIBRARY = [
  { id:'LIB-uptime',    name:'Operational uptime',         desc:'Per-site / per-asset uptime and SLA breach summary',                       icon:'activity'    },
  { id:'LIB-energy',    name:'Energy consumption',         desc:'Load, generation, and storage flows across the selected window',           icon:'zap'         },
  { id:'LIB-anomaly',   name:'Anomaly summary',            desc:'Vibration drift, thermal outliers, and predictive maintenance flags',     icon:'alert-triangle' },
  { id:'LIB-compliance',name:'Regulatory compliance',      desc:'Threshold breach log + sign-off checklist for the reporting period',      icon:'shield'      },
  { id:'LIB-mesh',      name:'Mesh health',                desc:'Gateway throughput, missed heartbeats, retry counts, firmware drift',     icon:'router'      },
  { id:'LIB-cost',      name:'Operating cost · estimated', desc:'Modelled energy cost + maintenance hours by zone, monthly',                icon:'pound-sterling' },
];

const RUNS_HISTORY = [
  ['12 May 00:05','RPT-001','Daily operations rollup',     'Success','2.1s'],
  ['12 May 07:00','RPT-002','Weekly mesh health summary',  'Success','3.4s'],
  ['11 May 22:00','RPT-005','AGV utilisation',              'Success','1.8s'],
  ['11 May 00:05','RPT-001','Daily operations rollup',     'Success','2.3s'],
  ['10 May 00:05','RPT-001','Daily operations rollup',     'Failed · 1 retry','12.0s'],
  ['09 May 18:00','RPT-004','Battery cycle audit',         'Success','1.1s'],
];

const ReportsHeader = ({ scheduled }) => {
  const enabled = scheduled.filter(r => r.state==='enabled').length;
  return (
    <div data-kpi-strip style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', borderTop:'1px solid #EDEDED', borderBottom:'1px solid #EDEDED', background:'#FFF' }}>
      <MetricTile label="Scheduled reports"  value={`${scheduled.length}`} sub={`${enabled} enabled · ${scheduled.length-enabled} paused`} />
      <MetricTile label="Runs · last 7 days" value="38" delta="+12%" sub="of which 1 failed" />
      <MetricTile label="Templates"          value={`${LIBRARY.length}`} sub="library" />
      <MetricTile label="Avg run time"       value="2.4" unit="s" delta="-18%" sub="rolling 30d" />
    </div>
  );
};

const ScheduledTable = () => {
  const isMobile = useIsMobile();
  return (
    <Card pad={0}>
      <div style={{
        padding: isMobile ? '14px 16px' : '18px 24px',
        borderBottom:'1px solid #EDEDED', display:'flex', justifyContent:'space-between',
        alignItems:'center', gap:12, flexWrap:'wrap'
      }}>
        <div>
          <Eyebrow>Recurring</Eyebrow>
          <div style={{ fontSize:16, color:'#0A0F1F', marginTop:4 }}>Scheduled reports</div>
        </div>
        <Button kind="primary">+ New</Button>
      </div>

      {isMobile && SCHEDULED.map(r => (
        <div key={r.id} style={{
          padding:'14px 16px', borderBottom:'1px solid #EDEDED',
          display:'flex', flexDirection:'column', gap:10
        }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', gap:8 }}>
            <span style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:11, color:'#5A5E6E' }}>{r.id}</span>
            <StatusPill state={r.state==='enabled' ? 'ok' : 'idle'}>{r.state}</StatusPill>
          </div>
          <div style={{ fontSize:15, color:'#0A0F1F', lineHeight:1.3 }}>{r.name}</div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <Field label="Schedule" mono>{r.schedule}</Field>
            <Field label="Format · size" mono>{r.format} · {r.size}</Field>
          </div>
          <Field label="Recipients">{r.recipients.join(' · ')}</Field>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', gap:8 }}>
            <span style={{ fontSize:11, color:'#5A5E6E', fontFamily:'IBM Plex Mono, monospace' }}>Last · {r.lastRun}</span>
            <Button kind="ghost" style={{ padding:'7px 12px', fontSize:12 }}>Run now</Button>
          </div>
        </div>
      ))}

      {!isMobile && (
        <>
          <div style={{
            display:'grid', gridTemplateColumns:'100px 1fr 170px 1fr 120px 90px 120px 80px',
            padding:'12px 24px', borderBottom:'1px solid #EDEDED',
            fontSize:11, letterSpacing:'0.08em', textTransform:'uppercase', color:'#5A5E6E', fontWeight:500
          }}>
            <div>Id</div><div>Name</div><div>Schedule</div><div>Recipients</div>
            <div>Last run</div><div>State</div><div>Format · size</div><div></div>
          </div>
          {SCHEDULED.map(r => (
            <div key={r.id} style={{
              display:'grid', gridTemplateColumns:'100px 1fr 170px 1fr 120px 90px 120px 80px',
              padding:'14px 24px', borderBottom:'1px solid #EDEDED',
              fontSize:14, color:'#0A0F1F', alignItems:'center'
            }}>
              <div style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:13 }}>{r.id}</div>
              <div>{r.name}</div>
              <div style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:12, color:'#242739' }}>{r.schedule}</div>
              <div style={{ fontSize:13, color:'#242739' }}>{r.recipients.join(' · ')}</div>
              <div style={{ fontSize:13, color:'#5A5E6E', fontFamily:'IBM Plex Mono, monospace' }}>{r.lastRun}</div>
              <div><StatusPill state={r.state==='enabled' ? 'ok' : 'idle'}>{r.state}</StatusPill></div>
              <div style={{ fontSize:13, color:'#242739', fontFamily:'IBM Plex Mono, monospace' }}>{r.format} · {r.size}</div>
              <div style={{ textAlign:'right' }}>
                <button style={{ background:'none', border:'none', cursor:'pointer', color:'#3A6FF8', font:"400 13px 'IBM Plex Sans'" }}>Run now</button>
              </div>
            </div>
          ))}
        </>
      )}
    </Card>
  );
};

const LibraryGrid = () => (
  <Card pad={0}>
    <div style={{ padding:'18px 24px', borderBottom:'1px solid #EDEDED' }}>
      <Eyebrow>Templates</Eyebrow>
      <div style={{ fontSize:18, color:'#0A0F1F', marginTop:4 }}>Report library</div>
      <div style={{ fontSize:13, color:'#5A5E6E', marginTop:4 }}>Run any template now or wire it to a schedule.</div>
    </div>
    <div data-collapse-md style={{ display:'grid', gridTemplateColumns:'repeat(3, 1fr)' }}>
      {LIBRARY.map((t, i) => (
        <div key={t.id} style={{
          padding:'24px', borderRight: (i%3 !== 2) ? '1px solid #EDEDED' : 'none',
          borderBottom: '1px solid #EDEDED', cursor:'pointer',
          transition:'background 200ms cubic-bezier(0.68,0.01,0.58,0.75)'
        }}
        onMouseOver={e => e.currentTarget.style.background = '#FAFBFC'}
        onMouseOut={e => e.currentTarget.style.background = '#FFF'}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:14 }}>
            <i data-lucide={t.icon} style={{ width:20, height:20, color:'#3A6FF8' }} />
            <span style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:11, color:'#5A5E6E' }}>{t.id}</span>
          </div>
          <div style={{ fontSize:18, fontWeight:400, color:'#0A0F1F', letterSpacing:'-0.02em' }}>{t.name}</div>
          <div style={{ fontSize:13, color:'#5A5E6E', marginTop:8, lineHeight:1.5 }}>{t.desc}</div>
          <div style={{ display:'flex', gap:8, marginTop:18 }}>
            <Button kind="ghost" style={{ padding:'7px 14px' }}>Run now</Button>
            <Button kind="subtle" style={{ padding:'7px 14px' }}>Schedule</Button>
          </div>
        </div>
      ))}
    </div>
  </Card>
);

const RunsHistory = () => {
  const isMobile = useIsMobile();
  return (
    <Card pad={0}>
      <div style={{
        padding: isMobile ? '14px 16px' : '18px 24px',
        borderBottom:'1px solid #EDEDED'
      }}>
        <Eyebrow>Activity</Eyebrow>
        <div style={{ fontSize:16, color:'#0A0F1F', marginTop:4 }}>Recent runs</div>
      </div>
      <div>
        {RUNS_HISTORY.map((r,i) => {
          const failed = r[3].startsWith('Failed');
          if (isMobile) {
            return (
              <div key={i} style={{
                padding:'12px 16px', borderBottom:'1px solid #EDEDED',
                display:'flex', flexDirection:'column', gap:6
              }}>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', gap:8 }}>
                  <span style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:12, color:'#5A5E6E' }}>{r[0]}</span>
                  <span style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:12, color:'#0A0F1F' }}>{r[1]}</span>
                </div>
                <div style={{ fontSize:14, color:'#0A0F1F' }}>{r[2]}</div>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', gap:8 }}>
                  <span style={{ fontSize:12, color: failed ? '#C44A4A' : '#242739' }}>{r[3]}</span>
                  <span style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:11, color:'#5A5E6E' }}>{r[4]}</span>
                </div>
              </div>
            );
          }
          return (
            <div key={i} style={{
              display:'grid', gridTemplateColumns:'130px 110px 1fr 160px 70px',
              padding:'12px 24px', borderBottom:'1px solid #EDEDED',
              fontSize:13, color:'#0A0F1F', alignItems:'center'
            }}>
              <span style={{ fontFamily:'IBM Plex Mono, monospace', color:'#5A5E6E' }}>{r[0]}</span>
              <span style={{ fontFamily:'IBM Plex Mono, monospace' }}>{r[1]}</span>
              <span>{r[2]}</span>
              <span style={{ color: failed ? '#C44A4A' : '#242739' }}>{r[3]}</span>
              <span style={{ textAlign:'right', fontFamily:'IBM Plex Mono, monospace', color:'#5A5E6E' }}>{r[4]}</span>
            </div>
          );
        })}
      </div>
    </Card>
  );
};

// Donut + stacked bar visualising recent runs
const RunsBreakdown = () => {
  const success = RUNS_HISTORY.filter(r => r[3].startsWith('Success')).length;
  const failed  = RUNS_HISTORY.filter(r => r[3].startsWith('Failed')).length;
  return (
    <Donut
      title="Runs · last 7 days"
      total={RUNS_HISTORY.length}
      totalLabel="executions"
      slices={[
        { label:'Success', value:success, color:'#3A6FF8' },
        { label:'Failed',  value:failed,  color:'#C44A4A' },
      ]}
    />
  );
};

const ReportsByCategory = () => (
  <StackedBar
    title="Scheduled reports by category"
    bars={[
      { label:'Operations', segments:[
        { value:1, color:'#3A6FF8', label:'Daily' },
        { value:1, color:'#7A9CFF', label:'Weekly' },
      ]},
      { label:'Energy',     segments:[
        { value:1, color:'#3A6FF8', label:'Daily' },
        { value:1, color:'#7A9CFF', label:'Weekly' },
      ]},
      { label:'Compliance', segments:[
        { value:1, color:'#0A0F1F', label:'Monthly' },
      ]},
      { label:'Logistics',  segments:[
        { value:1, color:'#3A6FF8', label:'Daily' },
      ]},
    ]}
  />
);

const Reports = () => (
  <div>
    <ReportsHeader scheduled={SCHEDULED} />
    <div data-pad-md style={{ padding:32, background:'#F6F7F9', display:'flex', flexDirection:'column', gap:24 }}>
      <div data-collapse-md style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:24 }}>
        <RunsBreakdown />
        <ReportsByCategory />
      </div>
      <div data-table-scroll><ScheduledTable /></div>
      <LibraryGrid />
      <div data-table-scroll><RunsHistory /></div>
    </div>
  </div>
);

Object.assign(window, { Reports });
