import React from 'react';
import { Svg, G } from 'react-native-svg';
import * as d3 from 'd3';
import { Dimensions } from 'react-native';
import { Line } from './line';
import { YAxis } from './y-axis';
import { XAxis } from './x-axis';
import { SBox } from '../../common/s-components/layout/s-box';
// import { fp as _ } from '../../common/utils/fp';
import { XAxisLabels } from './x-axis-labels';
import { YAxisLabels } from './y-axis-labels';
import { GRAPH_PADDING_TOP_RATIO } from '../constants';
import { TCoordinates, TGraphMaxes } from '../../common/types';
import { SGraphTitleSmall } from '../s-components/s-graph-title-small';

type TProps = {
  title?: string;
  dotted: TCoordinates;
  maxes: TGraphMaxes;
  ticks: number[];
  variant?: string;
  hideXAxis?: boolean;
};

const graphInnerHeight = 92;
const paddingTop = 20;
const vOffset = 16;
const topYLabelOffset = 16;
const width = Dimensions.get('window').width - 32;

export const LineGraphInner: React.FC<TProps> = props => {
  const {
    dotted,
    ticks,
    title,
    variant,
    hideXAxis,
    maxes: { xMin, xMax, yMax } = {},
  } = props;
  const getScales = () => {
    const xScale = d3
      .scaleLinear()
      .domain([xMin!, xMax!])
      .range([vOffset, width - vOffset]);
    const yScale = d3
      .scaleLinear()
      .domain([0, yMax!])
      .range([graphInnerHeight, paddingTop]);

    return { xScale, yScale };
  };

  const { xScale, yScale } = getScales();
  const yTicks = [0, yMax];
  const graphMax = yMax! / GRAPH_PADDING_TOP_RATIO;
  const svgHeight = hideXAxis ? 113 : 123;

  return (
    <SBox>
      <SBox px={16}>
        <SGraphTitleSmall>{title}</SGraphTitleSmall>
      </SBox>
      <SBox height={svgHeight}>
        <Svg height="100%" width={width}>
          <YAxis ticks={yTicks} scale={yScale} xOffsetRight={width} />
          <YAxisLabels
            ticks={yTicks}
            scale={yScale}
            offsetLeft={vOffset}
            offsetTop={topYLabelOffset}
            axisExclusion
          />

          {!hideXAxis ? (
            <>
              <XAxis
                ticks={ticks}
                scale={xScale}
                yOffset={graphInnerHeight}
                ticksVariant="edge"
              />
              <XAxisLabels
                ticks={ticks}
                scale={xScale}
                yOffset={graphInnerHeight}
                ticksVariant="edge"
              />
            </>
          ) : null}

          <G transform="translate(0, 0)">
            {dotted ? (
              <Line
                graphMax={graphMax}
                variant={variant}
                data={dotted}
                xScale={xScale}
                yScale={yScale}
              />
            ) : null}
          </G>
        </Svg>
      </SBox>
    </SBox>
  );
};

LineGraphInner.defaultProps = {
  title: 'STREAMS',
  variant: 'variant2',
  hideXAxis: false,
};
