/* eslint-disable */
/* =========================================================
   TEO IoT Dashboard — Settings.
   Tabs: Workspace · Users · Integrations · Mesh · API · Billing.
   Workspace and Integrations are the primary surfaces; the
   others are stubbed in the same TEO grammar.
   ========================================================= */

const SETTINGS_TABS = [
  ['workspace',    'Workspace'],
  ['users',        'Users'],
  ['integrations', 'Integrations'],
  ['mesh',         'Mesh'],
  ['api',          'API & tokens'],
  ['billing',      'Billing'],
];

const SettingsField = ({ label, hint, children, mono }) => (
  <div data-collapse-md style={{ display:'grid', gridTemplateColumns:'220px 1fr', gap:24, padding:'18px 0', borderBottom:'1px solid #EDEDED', alignItems:'start' }}>
    <div>
      <div style={{ fontSize:14, color:'#0A0F1F' }}>{label}</div>
      {hint && <div style={{ fontSize:12, color:'#5A5E6E', marginTop:4, lineHeight:1.5 }}>{hint}</div>}
    </div>
    <div style={{ fontFamily: mono ? "'IBM Plex Mono', monospace" : "'IBM Plex Sans'" }}>{children}</div>
  </div>
);

const TextInput = ({ value, mono, ...rest }) => (
  <input defaultValue={value} {...rest} style={{
    background:'transparent', border:'1px solid #878787', borderRadius:0,
    padding:'10px 14px', width:'100%', maxWidth:480,
    font: mono ? "400 13px 'IBM Plex Mono', monospace" : "400 14px 'IBM Plex Sans'", color:'#0A0F1F'
  }} />
);

const Toggle = ({ on, onChange }) => (
  <button onClick={() => onChange && onChange(!on)} style={{
    width:42, height:22, padding:2, background: on ? '#0A0F1F' : '#EDEDED',
    border:'1px solid '+(on?'#0A0F1F':'#878787'), borderRadius:0, cursor:'pointer',
    display:'flex', alignItems:'center', justifyContent: on ? 'flex-end' : 'flex-start',
    transition:'background 200ms cubic-bezier(0.68,0.01,0.58,0.75)'
  }}>
    <span style={{ width:14, height:14, background: on ? '#7A9CFF' : '#FFF', display:'block' }} />
  </button>
);

const WorkspaceTab = ({ site, sites }) => {
  const [emails, setEmails] = React.useState(true);
  const [slack,  setSlack]  = React.useState(true);
  const [pager,  setPager]  = React.useState(false);
  return (
    <Card pad={0}>
      <div style={{ padding:'18px 24px', borderBottom:'1px solid #EDEDED' }}>
        <Eyebrow>Workspace</Eyebrow>
        <div style={{ fontSize:18, color:'#0A0F1F', marginTop:4 }}>General</div>
      </div>
      <div style={{ padding:'4px 24px 24px' }}>
        <SettingsField label="Workspace name" hint="Shown in nav, reports, and audit log.">
          <TextInput value="National Grid" />
        </SettingsField>
        <SettingsField label="Default site" hint="The site loaded when operators sign in.">
          <select defaultValue={site.id} style={{ background:'transparent', border:'1px solid #878787', borderRadius:0, padding:'10px 14px', font:"400 14px 'IBM Plex Sans'", width:'100%', maxWidth:480 }}>
            {sites.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
          </select>
        </SettingsField>
        <SettingsField label="Timezone" hint="All timestamps in the UI render in this zone.">
          <select defaultValue="Europe/London" style={{ background:'transparent', border:'1px solid #878787', borderRadius:0, padding:'10px 14px', font:"400 14px 'IBM Plex Sans'", width:'100%', maxWidth:480 }}>
            <option>Europe/London</option><option>UTC</option><option>America/New_York</option>
          </select>
        </SettingsField>
        <SettingsField label="Telemetry retention" hint="High-resolution data is kept hot for this window; older data rolls into 5-minute aggregates.">
          <SegmentedControl value="30 days" onChange={() => {}} options={['7 days','30 days','90 days','1 year']} />
        </SettingsField>
        <SettingsField label="Alert channels" hint="Where alerts route. Critical alerts always page on-call regardless.">
          <div style={{ display:'flex', flexDirection:'column', gap:14 }}>
            <div style={{ display:'flex', alignItems:'center', gap:14 }}><Toggle on={emails} onChange={setEmails} /> <span style={{ fontSize:14 }}>Email · ops@teo.consulting</span></div>
            <div style={{ display:'flex', alignItems:'center', gap:14 }}><Toggle on={slack}  onChange={setSlack}  /> <span style={{ fontSize:14 }}>Slack · #ng-alerts</span></div>
            <div style={{ display:'flex', alignItems:'center', gap:14 }}><Toggle on={pager}  onChange={setPager}  /> <span style={{ fontSize:14 }}>PagerDuty · default escalation</span></div>
          </div>
        </SettingsField>
        <div style={{ display:'flex', gap:10, paddingTop:18 }}>
          <Button kind="primary">Save changes</Button>
          <Button kind="subtle">Discard</Button>
        </div>
      </div>
    </Card>
  );
};

const INTEGRATIONS = [
  { id:'mqtt',     name:'MQTT broker',    desc:'Subscribe to telemetry topics from gateways and bridge to the platform.', state:'connected',    icon:'router',       meta:'wss://mqtt.teo.io · QoS 1' },
  { id:'snowflake',name:'Snowflake',      desc:'Mirror aggregated telemetry into the data warehouse on a daily rollup.',  state:'connected',    icon:'database',     meta:'TEO_PROD · WAREHOUSE_S' },
  { id:'slack',    name:'Slack',          desc:'Route alert and report notifications to channels.',                       state:'connected',    icon:'message-square', meta:'teo-grid · 4 channels' },
  { id:'pagerduty',name:'PagerDuty',      desc:'Escalate critical alerts to the on-call rotation.',                       state:'connected',    icon:'phone',        meta:'Production · Tier 1' },
  { id:'teams',    name:'Microsoft Teams',desc:'Mirror Slack alerts into a Teams channel for enterprise environments.',   state:'disconnected', icon:'message-square', meta:null },
  { id:'webhook',  name:'Generic webhook',desc:'Push any platform event to an arbitrary HTTPS endpoint with retries.',    state:'disconnected', icon:'link',         meta:null },
  { id:'opcua',    name:'OPC-UA gateway', desc:'Bridge legacy SCADA assets via an OPC-UA-to-MQTT translator.',             state:'disconnected', icon:'cpu',          meta:null },
  { id:'iam',      name:'SSO · SAML',     desc:'Federate operator access against your identity provider.',                state:'connected',    icon:'shield',       meta:'Okta · 14 users' },
];

const IntegrationsTab = () => (
  <Card pad={0}>
    <div style={{ padding:'18px 24px', borderBottom:'1px solid #EDEDED' }}>
      <Eyebrow>Connectors</Eyebrow>
      <div style={{ fontSize:18, color:'#0A0F1F', marginTop:4 }}>Integrations</div>
    </div>
    <div data-collapse-md style={{ display:'grid', gridTemplateColumns:'1fr 1fr' }}>
      {INTEGRATIONS.map((it, i) => (
        <div key={it.id} style={{
          padding:'20px 24px',
          borderRight: (i%2===0) ? '1px solid #EDEDED' : 'none',
          borderBottom:'1px solid #EDEDED',
          display:'grid', gridTemplateColumns:'40px 1fr auto', gap:16, alignItems:'center'
        }}>
          <div style={{ width:36, height:36, background:'#F6F7F9', border:'1px solid #EDEDED', display:'flex', alignItems:'center', justifyContent:'center' }}>
            <i data-lucide={it.icon} style={{ width:16, height:16, color:'#0A0F1F' }} />
          </div>
          <div>
            <div style={{ display:'flex', alignItems:'center', gap:10 }}>
              <span style={{ fontSize:15, color:'#0A0F1F' }}>{it.name}</span>
              <StatusPill state={it.state==='connected' ? 'ok' : 'idle'}>{it.state}</StatusPill>
            </div>
            <div style={{ fontSize:12, color:'#5A5E6E', marginTop:4, lineHeight:1.5 }}>{it.desc}</div>
            {it.meta && <div style={{ fontFamily:'IBM Plex Mono, monospace', fontSize:11, color:'#3A6FF8', marginTop:6 }}>{it.meta}</div>}
          </div>
          <Button kind={it.state==='connected' ? 'subtle' : 'primary'}>
            {it.state==='connected' ? 'Configure' : 'Connect'}
          </Button>
        </div>
      ))}
    </div>
  </Card>
);

const USERS = [
  { id:'usr-001', name:'Martin Chadwick',  email:'martin@thirdeyeopen.io', role:'Owner',      added:'Jan 2026', last:'2 min ago',  mfa:true  },
  { id:'usr-002', name:'Jamie Doyle',      email:'jd@teo.consulting',      role:'Operator',   added:'Feb 2026', last:'12 min ago', mfa:true  },
  { id:'usr-003', name:'Priya Kapoor',     email:'pk@teo.consulting',      role:'Operator',   added:'Feb 2026', last:'1 h ago',    mfa:true  },
  { id:'usr-004', name:'Tom Harker',       email:'tom@nationalgrid',       role:'Viewer',     added:'Mar 2026', last:'Yesterday',  mfa:false },
  { id:'usr-005', name:'Compliance auto',  email:'compliance@ng',          role:'Service · read', added:'Apr 2026', last:'07:00',  mfa:true  },
];

const UsersTab = () => {
  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>Access</Eyebrow>
          <div style={{ fontSize:16, color:'#0A0F1F', marginTop:4 }}>Users & roles</div>
        </div>
        <Button kind="primary">+ Invite</Button>
      </div>

      {isMobile && USERS.map(u => (
        <div key={u.id} style={{
          padding:'14px 16px', borderBottom:'1px solid #EDEDED',
          display:'flex', flexDirection:'column', gap:10
        }}>
          <div style={{ display:'flex', alignItems:'center', gap:12 }}>
            <div style={{ width:36, height:36, borderRadius:'50%', background:'#11172B', color:'#FFF', display:'flex', alignItems:'center', justifyContent:'center', fontSize:12, flexShrink:0 }}>
              {u.name.split(' ').map(s=>s[0]).join('').slice(0,2)}
            </div>
            <div style={{ minWidth:0, flex:1 }}>
              <div style={{ fontSize:14, color:'#0A0F1F' }}>{u.name}</div>
              <div style={{ fontSize:11, color:'#5A5E6E', fontFamily:'IBM Plex Mono, monospace', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{u.email}</div>
            </div>
            {u.mfa ? <StatusPill state="ok">MFA on</StatusPill> : <StatusPill state="warn">MFA off</StatusPill>}
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8 }}>
            <Field label="Role">{u.role}</Field>
            <Field label="Added">{u.added}</Field>
            <Field label="Last active">{u.last}</Field>
          </div>
        </div>
      ))}

      {!isMobile && (
        <>
          <div style={{
            display:'grid', gridTemplateColumns:'1fr 1fr 140px 110px 130px 80px 80px',
            padding:'12px 24px', borderBottom:'1px solid #EDEDED',
            fontSize:11, letterSpacing:'0.08em', textTransform:'uppercase', color:'#5A5E6E', fontWeight:500
          }}>
            <div>Name</div><div>Email</div><div>Role</div><div>Added</div><div>Last active</div><div>MFA</div><div></div>
          </div>
          {USERS.map(u => (
            <div key={u.id} style={{
              display:'grid', gridTemplateColumns:'1fr 1fr 140px 110px 130px 80px 80px',
              padding:'14px 24px', borderBottom:'1px solid #EDEDED',
              fontSize:14, color:'#0A0F1F', alignItems:'center'
            }}>
              <div style={{ display:'flex', alignItems:'center', gap:12 }}>
                <div style={{ width:30, height:30, borderRadius:'50%', background:'#11172B', color:'#FFF', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11 }}>
                  {u.name.split(' ').map(s=>s[0]).join('').slice(0,2)}
                </div>
                <span>{u.name}</span>
              </div>
              <div style={{ fontSize:13, color:'#242739', fontFamily:'IBM Plex Mono, monospace' }}>{u.email}</div>
              <div style={{ fontSize:13 }}>{u.role}</div>
              <div style={{ fontSize:13, color:'#5A5E6E' }}>{u.added}</div>
              <div style={{ fontSize:13, color:'#5A5E6E' }}>{u.last}</div>
              <div>{u.mfa ? <StatusPill state="ok">On</StatusPill> : <StatusPill state="warn">Off</StatusPill>}</div>
              <div style={{ textAlign:'right' }}>
                <button style={{ background:'none', border:'none', cursor:'pointer', color:'#3A6FF8', font:"400 13px 'IBM Plex Sans'" }}>Edit</button>
              </div>
            </div>
          ))}
        </>
      )}
    </Card>
  );
};

const MeshTab = () => (
  <Card pad={0}>
    <div style={{ padding:'18px 24px', borderBottom:'1px solid #EDEDED' }}>
      <Eyebrow>Topology</Eyebrow>
      <div style={{ fontSize:18, color:'#0A0F1F', marginTop:4 }}>Mesh configuration</div>
    </div>
    <div style={{ padding:'4px 24px 24px' }}>
      <SettingsField label="Heartbeat interval" hint="How often each device pings its gateway. Lower = faster anomaly detection, more traffic.">
        <SegmentedControl value="30s" onChange={()=>{}} options={['10s','30s','1m','5m']} />
      </SettingsField>
      <SettingsField label="Heartbeat tolerance" hint="Consecutive missed heartbeats before a device is flagged offline.">
        <SegmentedControl value="3" onChange={()=>{}} options={['1','2','3','5','10']} />
      </SettingsField>
      <SettingsField label="Telemetry sample rate" hint="Per-sensor sampling cadence at the edge.">
        <TextInput value="1 Hz" />
      </SettingsField>
      <SettingsField label="Edge buffering" hint="If the gateway loses connection, how many minutes of telemetry to buffer locally before dropping samples.">
        <TextInput value="60 min" />
      </SettingsField>
      <SettingsField label="Mesh certificate" hint="Used for mutual-TLS between devices and gateway. Rotates automatically every 90 days." mono>
        <div style={{ display:'flex', gap:8, alignItems:'center' }}>
          <code style={{ background:'#F6F7F9', padding:'6px 10px', fontSize:12 }}>teo-mesh-2026-05-rotated</code>
          <Button kind="subtle">Rotate now</Button>
        </div>
      </SettingsField>
    </div>
  </Card>
);

const ApiTab = () => (
  <Card pad={0}>
    <div style={{ padding:'18px 24px', borderBottom:'1px solid #EDEDED' }}>
      <Eyebrow>Programmatic</Eyebrow>
      <div style={{ fontSize:18, color:'#0A0F1F', marginTop:4 }}>API & service tokens</div>
    </div>
    <div style={{ padding:'24px' }}>
      <div style={{ fontSize:13, color:'#5A5E6E', marginBottom:18 }}>
        Tokens authenticate machine-to-machine access. Scope tokens narrowly — least-privilege by default.
      </div>
      {[
        ['TKN-A',  'compliance-monthly-export', 'read · reports',                       'Apr 2026', '01 May 06:00'],
        ['TKN-B',  'snowflake-rollup',          'read · telemetry',                     'Mar 2026', '12 May 00:05'],
        ['TKN-C',  'edge-firmware-ota',         'write · firmware',                     'Feb 2026', '11 May 22:00'],
      ].map(r => (
        <div key={r[0]} style={{ display:'grid', gridTemplateColumns:'90px 1fr 1fr 120px 130px 80px', padding:'14px 0', borderBottom:'1px solid #EDEDED', alignItems:'center', fontSize:13 }}>
          <span style={{ fontFamily:'IBM Plex Mono, monospace' }}>{r[0]}</span>
          <span>{r[1]}</span>
          <span style={{ fontFamily:'IBM Plex Mono, monospace', color:'#3A6FF8' }}>{r[2]}</span>
          <span style={{ color:'#5A5E6E' }}>Created {r[3]}</span>
          <span style={{ color:'#5A5E6E' }}>{r[4]}</span>
          <span style={{ textAlign:'right' }}>
            <button style={{ background:'none', border:'none', cursor:'pointer', color:'#C44A4A', font:"400 13px 'IBM Plex Sans'" }}>Revoke</button>
          </span>
        </div>
      ))}
      <div style={{ marginTop:18 }}>
        <Button kind="primary">+ Create token</Button>
      </div>
    </div>
  </Card>
);

const BillingTab = () => (
  <div style={{ display:'flex', flexDirection:'column', gap:24 }}>
    <Card pad={0}>
      <div style={{ padding:'18px 24px', borderBottom:'1px solid #EDEDED' }}>
        <Eyebrow>Plan & usage</Eyebrow>
        <div style={{ fontSize:18, color:'#0A0F1F', marginTop:4 }}>Billing</div>
      </div>
      <div data-kpi-strip style={{ display:'grid', gridTemplateColumns:'repeat(3, 1fr)', borderBottom:'1px solid #EDEDED' }}>
        <MetricTile label="Plan"            value="Operate" sub="annual · seat-based" />
        <MetricTile label="Devices"         value="29 / 200" delta="+11" sub="across all sites" />
        <MetricTile label="Telemetry · 30d" value="2.4" unit="GB" delta="+11%" sub="includes rollups" />
      </div>
      <div style={{ padding:24, display:'flex', gap:10 }}>
        <Button kind="ghost">View invoices</Button>
        <Button kind="subtle">Update payment method</Button>
      </div>
    </Card>
    <RadialBar
      title="Plan usage · against Operate tier limits"
      rings={[
        { label:'Devices',           value:29,  max:200,  color:'#3A6FF8', unit:''     },
        { label:'Telemetry (GB/mo)', value:2.4, max:10,   color:'#7A9CFF', unit:'GB'   },
        { label:'Active users',      value:14,  max:50,   color:'#23459E', unit:''     },
        { label:'API requests (k/d)',value:42,  max:200,  color:'#0A0F1F', unit:'k/d'  },
      ]}
    />
  </div>
);

const Settings = ({ site, sites }) => {
  const [tab, setTab] = React.useState('workspace');
  return (
    <div data-pad-md style={{ padding:32, background:'#F6F7F9', minHeight:'calc(100vh - 73px)' }}>
      <div data-collapse-md style={{ display:'grid', gridTemplateColumns:'220px 1fr', gap:24, alignItems:'start' }}>
        <nav className="teo-settings-tabs" style={{ display:'flex', flexDirection:'column', background:'#FFF', border:'1px solid #EDEDED' }}>
          {SETTINGS_TABS.map(([k, l]) => (
            <button key={k} onClick={() => setTab(k)} style={{
              padding:'12px 16px',
              background: tab===k ? '#0A0F1F' : 'transparent',
              color: tab===k ? '#FFF' : '#242739',
              border:'none', borderBottom:'1px solid #EDEDED',
              textAlign:'left', cursor:'pointer',
              font:"400 14px 'IBM Plex Sans'",
              borderLeft: tab===k ? '2px solid #7A9CFF' : '2px solid transparent'
            }}>{l}</button>
          ))}
        </nav>
        <div>
          {tab === 'workspace'    && <WorkspaceTab site={site} sites={sites} />}
          {tab === 'users'        && <UsersTab />}
          {tab === 'integrations' && <IntegrationsTab />}
          {tab === 'mesh'         && <MeshTab />}
          {tab === 'api'          && <ApiTab />}
          {tab === 'billing'      && <BillingTab />}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Settings });
