/**
 * @format
 */

import React, {FC, useEffect, useState} from 'react'
import {
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Brush,
  LineChart,
  Line,
  ResponsiveContainer,
  Label,
  Legend,
  LabelList
} from 'recharts'
import {formatLineChartData, groupArrayBy, nFormatter, setChartTicks, tickFormatter} from '../../common/utils'
import { useChartActiveDataPoints } from '../../hooks/useChartActiveDataPoints'
import {
  chartColors_blue,
  LineChartOptions,
  TimePeriods
} from '../../types/types'
import {CustomLabel, CustomTooltipDouble} from './ChartElemets'

export const LineChartComponent: FC<LineChartOptions> = ({
  data,
  xAxisLabeL,
  yAxisLabeL,
  currentTimePeriod
}) => {
  // a perm solution to group data by regions for different lines
  const [activeLegends, handleDotClick] = useChartActiveDataPoints()
  const [processedData, setProcessedData] = useState<any>(data)
  const [dataKeys, setDataKeys] = useState(new Set<any>())

  useEffect(()=> {
    const {processedData, dataKeys} = formatLineChartData(groupArrayBy('X_AXIS_VALUE', data))
    setProcessedData(processedData)
    setDataKeys(dataKeys)
  }, [data])

  return (
    <ResponsiveContainer width={'100%'} height={410}>
      <LineChart
        data={processedData}
        margin={{
          top: 40,
          right: 20,
          bottom: 40,
          left: 20
        }}
        onClick={(chartState, event) => {
          handleDotClick(chartState, event)
        }}
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis
          allowDataOverflow
          dataKey="date"
          stroke={'#111928'}
          tickLine={false}
          fontSize={'12px'}
          ticks={setChartTicks(processedData, 'date')}
          tickFormatter={tick => tickFormatter(tick, currentTimePeriod)}>
          <Label
            value={xAxisLabeL}
            offset={16}
            position="bottom"
            fontSize={'12px'}
          />
        </XAxis>
        <YAxis
          fontSize={'12px'}
          name={'price'}
          stroke={'#111928'}
          tickLine={false}
          tickFormatter={tick => nFormatter(tick, 3)}>
          <Label
            value={yAxisLabeL}
            offset={10}
            angle={-90}
            position="left"
            fontSize={'12px'}
          />
        </YAxis>
        <Tooltip
          content={
            <CustomTooltipDouble
              headingType={
                currentTimePeriod === TimePeriods.Montly ? 'date' : 'string'
              }
              headingKeyName="date"
              elements={[
                {
                  propertyNames: ['', '75th', 'Median', '25th'],
                  propertyKeyNames: ['address', '75', 'price', '25'],
                  color: '#111928',
                  rightColumnKey: 'numOfTransactions'
                }
              ]}
            />
          }
        />
        <Brush
          y={340}
          dataKey="date"
          height={50}
          fill={'transparent'}
          stroke={'#a0a5b0'}
          strokeOpacity={1}
          travellerWidth={20}
          traveller={
            <svg
              width="50"
              height="50"
              viewBox="0 0 28 29"
              fill="none"
              xmlns="http://www.w3.org/2000/svg">
              <rect
                y="28.1875"
                width="28"
                height="28"
                rx="14"
                transform="rotate(-90 0 28.1875)"
                fill="#E5E7EB"
              />
              <path
                fillRule="evenodd"
                clipRule="evenodd"
                d="M7 14.1877C7.00006 13.9225 7.10545 13.6682 7.293 13.4807L10.293 10.4807C10.4816 10.2986 10.7342 10.1978 10.9964 10.2C11.2586 10.2023 11.5094 10.3075 11.6948 10.4929C11.8802 10.6783 11.9854 10.9291 11.9877 11.1913C11.99 11.4535 11.8892 11.7061 11.707 11.8947L9.414 14.1877L11.707 16.4807C11.8892 16.6693 11.99 16.9219 11.9877 17.1841C11.9854 17.4463 11.8802 17.6971 11.6948 17.8825C11.5094 18.0679 11.2586 18.1731 10.9964 18.1754C10.7342 18.1777 10.4816 18.0769 10.293 17.8947L7.293 14.8947C7.10545 14.7072 7.00006 14.4529 7 14.1877ZM16.293 17.8947C16.1055 17.7072 16.0002 17.4529 16.0002 17.1877C16.0002 16.9225 16.1055 16.6682 16.293 16.4807L18.586 14.1877L16.293 11.8947C16.1108 11.7061 16.01 11.4535 16.0123 11.1913C16.0146 10.9291 16.1198 10.6783 16.3052 10.4929C16.4906 10.3075 16.7414 10.2023 17.0036 10.2C17.2658 10.1978 17.5184 10.2986 17.707 10.4807L20.707 13.4807C20.8945 13.6682 20.9998 13.9225 20.9998 14.1877C20.9998 14.4529 20.8945 14.7072 20.707 14.8947L17.707 17.8947C17.5195 18.0822 17.2652 18.1875 17 18.1875C16.7348 18.1875 16.4805 18.0822 16.293 17.8947Z"
                fill="#111928"
              />
            </svg>
          }>
          <LineChart
            data={processedData}
            margin={{
              top: 40,
              right: 20,
              bottom: 40,
              left: 20
            }}>
            <CartesianGrid
              strokeDasharray={3}
              fill={'#F9FAFB'}
              horizontal={false}
            />
            <Line
              type="monotone"
              dataKey={`${Array.from(dataKeys)[dataKeys.size - 1]}.price`}
              dot={false}
            />
          </LineChart>
        </Brush>

        {Array.from(dataKeys).map((item, index) => (
          <Line
            key={index}
            type="natural"
            dataKey={`${item}.price`}
            stroke={chartColors_blue[index]}
            strokeWidth={3}
            dot={{fill: chartColors_blue[index], strokeWidth: 0.5}}
          >
            {index === dataKeys.size - 1 && <LabelList
              dataKey={'id'}
              position="top"
              content={items => (
                <CustomLabel
                  {...items}
                  activeLegends={activeLegends}
                  dataArray={processedData}
                  currentTimePeriod={currentTimePeriod}
                  tooltipType="double"
                />
              )}
            />}

          </Line>
        ))}
        <Legend
          verticalAlign="bottom"
          align="left"
          height={36}
          iconSize={10}
          payload={Array.from(dataKeys).map((item, index) => ({
            value: item,
            type: 'circle',
            color: chartColors_blue[index]
          }))}
          wrapperStyle={{position: 'absolute', bottom: '-40px'}}
        />
      </LineChart>
    </ResponsiveContainer>
  )
}
