import React from 'react'
import ReactApexChart from 'react-apexcharts'
import './styles.css'

import 'apexcharts/features/trellis'

// Nine services' p99 latency, one panel each. The grid answers "which
// service is misbehaving" (checkout is); CLICKING THAT HEADER answers "what
// exactly happened": the panel expands to the grid's full width with both
// axes readable, and the "All panels" breadcrumb puts the grid back. Zoom
// and legend state survive the round trip.
//
// Deterministic latencies so the e2e snapshot is stable.
function mulberry32(seed) {
  return function () {
    seed |= 0
    seed = (seed + 0x6d2b79f5) | 0
    var t = Math.imul(seed ^ (seed >>> 15), 1 | seed)
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296
  }
}

var SERVICES = [
  { name: 'gateway', seed: 3, base: 120 },
  { name: 'auth', seed: 11, base: 85 },
  { name: 'catalog', seed: 19, base: 140 },
  { name: 'search', seed: 27, base: 210 },
  { name: 'cart', seed: 35, base: 95 },
  { name: 'checkout', seed: 43, base: 150 },
  { name: 'payments', seed: 51, base: 180 },
  { name: 'shipping', seed: 59, base: 110 },
  { name: 'notifications', seed: 67, base: 70 },
]

function latency(seed, base, degradeFrom) {
  var rand = mulberry32(seed)
  var out = []
  var ts = new Date('01 Jan 2025').getTime()
  var val = base
  for (var i = 0; i < 72; i++) {
    val = Math.max(40, val + (rand() - 0.5) * base * 0.1)
    var v = val
    // checkout degrades in steps after hour 40: the shape you promote to see.
    if (degradeFrom && i >= degradeFrom) {
      v = val + Math.min(320, (i - degradeFrom) * 14)
    }
    out.push([ts, Math.round(v)])
    ts += 3600000 // hourly
  }
  return out
}

var latencySeries = SERVICES.map(function (s) {
  return {
    name: 'p99 latency',
    service: s.name,
    data: latency(s.seed, s.base, s.name === 'checkout' ? 40 : 0),
  }
})

const ApexChart = () => {
  const [state, setState] = React.useState({
    series: latencySeries,
    options: {
      chart: {
        id: 'latencyTrellis',
        type: 'line',
        animations: {
          enabled: false,
        },
      },
      trellis: {
        by: 'service',
        minPanelWidth: 250,
        panelHeight: 140,
        gap: 12,
      },
      colors: ['#0891B2'],
      stroke: {
        width: 2,
        curve: 'straight',
      },
      xaxis: {
        type: 'datetime',
      },
      yaxis: {
        labels: {
          formatter: function (val) {
            return Math.round(val) + ' ms'
          },
        },
      },
      dataLabels: {
        enabled: false,
      },
      tooltip: {
        x: {
          format: 'dd MMM HH:mm',
        },
      },
    },
  })

  return (
    <div>
      <div className="wrap">
        <h1>p99 latency by service</h1>
        <p className="lead">
          Nine services at a glance, one obviously degrading. Click the
          <strong>checkout</strong> header: the panel expands to the grid's full
          width for a proper look, and "All panels" brings the grid back.
        </p>

        <div className="chart-wrap">
          <div id="chart">
            <ReactApexChart
              options={state.options}
              series={state.series}
              type="line"
            />
          </div>
        </div>

        <div className="note">
          Every cell header is a button: clicking it promotes that panel to the
          grid's full width (parked panels keep their state; a virtualized grid
          simply unmounts them) and a breadcrumb restores the grid. Clicking the
          promoted header again also restores. The same flow is scriptable:
          <code>chart.promotePanel('checkout')</code> and
          <code>chart.restorePanels()</code>. Set{' '}
          <code>trellis.promote: false</code> to make headers inert. Trellis is
          a premium feature; without a license it renders with a trial
          watermark.
        </div>
      </div>
    </div>
  )
}

export default ApexChart