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

import 'apexcharts/features/raincloud'

// Raw observations for one group: a Gaussian sample via the Box-Muller
// transform. The sample template seeds Math.random, so this renders
// identically across reloads. Raincloud takes the SAMPLE, and the library
// derives the density (cloud) and the five-number summary (box) from it.
function sample(mean, sd, n) {
  var points = []
  for (var k = 0; k < n; k++) {
    var u1 = Math.random(),
      u2 = Math.random()
    var g = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2)
    points.push(Math.round((mean + g * sd) * 10) / 10)
  }
  return points
}

const ApexChart = () => {
  const [state, setState] = React.useState({
    series: [
      {
        name: 'Weight gain',
        data: [
          { x: 'DD', points: sample(97, 26, 220) },
          { x: 'DR', points: sample(84, 20, 160) },
          { x: 'RD', points: sample(101, 27, 200) },
          { x: 'RR', points: sample(80, 22, 210) },
        ],
      },
    ],
    options: {
      chart: {
        type: 'raincloud',
        height: 460,
      },
      title: {
        text: 'Weight gain from birth to weaning, by genotype',
      },
      subtitle: {
        text: 'Each dot is one animal; box = quartiles, curve = density',
      },
      plotOptions: {
        bar: {
          distributed: true, // one colour per group
        },
      },
      legend: {
        show: false, // distributed colours make the legend redundant
      },
      yaxis: {
        title: {
          text: 'Weight gain (g/day)',
        },
      },
    },
  })

  return (
    <div>
      <div id="chart">
        <ReactApexChart
          options={state.options}
          series={state.series}
          type="raincloud"
          height={460}
        />
      </div>
    </div>
  )
}

export default ApexChart