import { Card, Radio, Skeleton, Tooltip as AntdToolTip, Typography } from "antd";
import React, { useState } from "react";
import { connect } from "react-redux";
import {
  CartesianGrid,
  Legend,
  ResponsiveContainer,
  Scatter,
  ScatterChart,
  Tooltip,
  XAxis,
  YAxis,
  ZAxis
} from "recharts";
import { createStructuredSelector } from "reselect";
import { selectReportLoading, selectScorecard } from "../../../redux/reporting/reporting.selectors";
import DataLabelAtom from "../../atoms/data-label/data-label.atom";
import ErrorResultAtom from "../../atoms/error-result/error-result.atom";
import { getDecimalPrecision } from "../../../util/decimalPrecision";

const mapStateToProps = createStructuredSelector({
  reportingLoading: selectReportLoading,
  scoreCard: selectScorecard
});
const mapDispatchToProps = (dispatch) => ({});
export default connect(mapStateToProps, mapDispatchToProps)(ReportingScatterChartMolecule);

export function ReportingScatterChartMolecule({ reportingLoading, scoreCard }) {
  const [type, setType] = useState("percent");

  if (reportingLoading) return <Skeleton active />;
  if (!scoreCard) return <ErrorResultAtom title="Error displaying score card data." />;

  const handleTypeChange = (e) => {
    setType(e.target.value);
  };
  const precision = getDecimalPrecision();
  return (
    <div>
      <div
        style={{
          marginTop: "1rem",
          marginBottom: "1rem",
          width: "100%",
          height: "30rem"
        }}
      >
        <div style={{ display: "flex", flexDirection: "row" }}>
          {type === "percent" && (
            <AntdToolTip
              placement="bottomLeft"
              title="Calculated as Actual Job RPS % less Target Job RPS %. E.g. 10% - 8% = 2%"
            >
              <Typography.Title level={4}>% Variance from Target</Typography.Title>
            </AntdToolTip>
          )}
          {type === "dollars" && (
            <AntdToolTip placement="bottomLeft" title="Calculated as Actual Job RPS $ less Target Job RPS $.">
              <Typography.Title level={4}>$ Variance from Target</Typography.Title>
            </AntdToolTip>
          )}

          <Radio.Group
            onChange={handleTypeChange}
            value={type}
            placeholder="Variance Type"
            style={{ marginLeft: "auto" }}
          >
            <Radio.Button value="percent">% - Percent</Radio.Button>
            <Radio.Button value="dollars">$ - Dollars</Radio.Button>
          </Radio.Group>
        </div>

        <ResponsiveContainer>
          <ScatterChart margin={{ top: 20, right: 20, bottom: 10, left: 10 }}>
            <CartesianGrid strokeDasharray="3 3" />
            {type === "percent" && (
              <XAxis
                dataKey="deviationPc"
                type="number"
                ticks={[-100, -75, -50, -25, 0, 25, 50, 75, 100]}
                domain={[-100, 100]}
                name="Deviation"
                unit="%"
              />
            )}
            {type === "dollars" && <XAxis dataKey="deviationDollars" type="number" name="Deviation ($)" />}

            <YAxis type="number" dataKey="age" name="Age" unit="Years" />
            <ZAxis dataKey="dbPriceSumAmt" name="DB Price Total" />
            <Tooltip
              content={({ payload }) => {
                const item = payload && payload[0] && payload[0].payload;
                if (!item) return null;
                return (
                  <Card title={item.clm_no}>
                    <DataLabelAtom label="Owner">{item.owner}</DataLabelAtom>
                    <DataLabelAtom label="Vehicle">{item.vehicle}</DataLabelAtom>
                    <DataLabelAtom label="Job RPS $">{item.jobRpsDollars.toFormat()}</DataLabelAtom>
                    <DataLabelAtom label="Job RPS %">{(item.jobRpsPc * 100).toFixed(precision)}%</DataLabelAtom>
                    <DataLabelAtom label="DB Price">{item.dbPriceSum.toFormat()}</DataLabelAtom>
                    <DataLabelAtom label="Variance %">{`${item.deviationPc.toFixed(precision)}%`}</DataLabelAtom>
                    <DataLabelAtom label="Variance $">${item.deviationDollars}</DataLabelAtom>
                  </Card>
                );
              }}
              cursor={{ strokeDasharray: "2 2", stroke: "tomato" }}
            />
            <Legend />
            {Object.keys(scoreCard.scatterChart).map((key, idx) => (
              <Scatter name={key} key={idx} data={scoreCard.scatterChart[key]} fill={colors[idx]}></Scatter>
            ))}
          </ScatterChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}

const colors = ["#0c344d", "#6cc314", "#f5782a", "#f5be2a", "#fbff90", "dodgerblue"];
