import { useState } from "react";
import ChartDraw from './ChartDraw.jsx';
import * as d3 from "d3";


const Chart = (props) => {
  const [ox, setOx] = useState("Страна");
  const [oy, setOy] = useState([true, false]);
  const [oyBuf, setOyBuf] = useState([true, false]);
  const [graphType, setGraphType] = useState(0);

  const handleSubmit = (event) => {
    event.preventDefault();
    setOx(event.target["ox"].value);
    setOy(oyBuf);
    setGraphType(event.target["graphType"].value);
  }
  const handleCheckboxes = (event)=>{
    let buf = [...oyBuf];
    buf[Number(event.target.id)]=event.target.checked;
    setOyBuf(buf);
    console.log(buf)

  }

  const createArrGraph = (data, key) => {
    const groupObj = d3.group(data, d => d[key]);
    let arrGraph = [];
    for (let entry of groupObj) {
      let minMax = d3.extent(entry[1].map(d => d['Высота']));
      arrGraph.push({ labelX: entry[0], values: minMax });
    }
    return arrGraph;
  }

  return (
    <>
      <h4>Визуализация</h4>
      <form onSubmit={handleSubmit} >
        <p> Значение по оси OX: </p>
        <div>
          <input type="radio" name="ox" value="Страна" defaultChecked={ox === "Страна"}  />
          Страна
          <br />
          <input  type="radio" name="ox" value="Год" defaultChecked={ox === "Год"}  />
          Год
          <br />
        </div>

        <p> Значение по оси OY </p>
        {(!oyBuf[0]&& !oyBuf[1]) && <span className="bad-selection"> Выберите хотя бы одно</span>}
        <div>
           <input id="0" type="checkbox" name="oy" defaultChecked={oyBuf[0] === true} onChange={handleCheckboxes} />
          Минимальная высота
          <br />
          <input id="1" type="checkbox" name="oy" defaultChecked={oyBuf[1] === true} onChange={handleCheckboxes}/>
          Максимальная высота 
         
        </div>
        <p>Тип диаграммы </p>
        <div>
          <select name="graphType" defaultValue={graphType}>
            <option value="0" >Точечная</option>
            <option value="1">Гистограма</option>
          </select>
        </div>

        <p>
          <button type="submit">Построить </button>
        </p>
      </form>
      <ChartDraw data={createArrGraph(props.data, ox)} ox={ox} minMax={oy} graphType={graphType} />
    </>
  )
}

export default Chart;