/**
 * @format
 */

import * as React from 'react'
import {Box, Heading, HStack, Text} from '@chakra-ui/react'
import {
  Line,
  CartesianGrid,
  XAxis,
  YAxis,
  Tooltip,
  Area,
  ComposedChart,
  ResponsiveContainer,
  Pie,
  PieChart,
  Cell,
  Legend
} from 'recharts'
import {nFormatter} from '../common/utils'
import {KeyValue} from '../types/types'

const transactionPrice = [
  {
    TRANSACTION_YEAR: '2018',
    MEDIAN_TRANSACTION_PRICE: '496000',
    MIN_TRANSACTION_PRICE: '120000',
    MAX_TRANSACTION_PRICE: '1300000'
  },
  {
    TRANSACTION_YEAR: '2019',
    MEDIAN_TRANSACTION_PRICE: '550000',
    MIN_TRANSACTION_PRICE: '230000',
    MAX_TRANSACTION_PRICE: '1220000'
  },
  {
    TRANSACTION_YEAR: '2020',
    MEDIAN_TRANSACTION_PRICE: '580000',
    MIN_TRANSACTION_PRICE: '100000',
    MAX_TRANSACTION_PRICE: '3800000'
  },
  {
    TRANSACTION_YEAR: '2021',
    MEDIAN_TRANSACTION_PRICE: '501500',
    MIN_TRANSACTION_PRICE: '270000',
    MAX_TRANSACTION_PRICE: '1575000'
  },
  {
    TRANSACTION_YEAR: '2022',
    MEDIAN_TRANSACTION_PRICE: '757500',
    MIN_TRANSACTION_PRICE: '272000',
    MAX_TRANSACTION_PRICE: '1170000'
  }
]

const PSFMedianData = [
  {
    TRANSACTION_YEAR: '2018',
    MEDIAN_TRANSACTION_PRICE: '496000',
    MAX_TRANSACTION_PRICE: '586000',
    MIN_TRANSACTION_PRICE: '386000'
  },
  {
    TRANSACTION_YEAR: '2019',
    MEDIAN_TRANSACTION_PRICE: '550000',
    MAX_TRANSACTION_PRICE: '660000',
    MIN_TRANSACTION_PRICE: '440000'
  },
  {
    TRANSACTION_YEAR: '2020',
    MEDIAN_TRANSACTION_PRICE: '580000',
    MAX_TRANSACTION_PRICE: '690000',
    MIN_TRANSACTION_PRICE: '470000'
  },
  {
    TRANSACTION_YEAR: '2021',
    MEDIAN_TRANSACTION_PRICE: '501500',
    MAX_TRANSACTION_PRICE: '621500',
    MIN_TRANSACTION_PRICE: '400500'
  },
  {
    TRANSACTION_YEAR: '2022',
    MEDIAN_TRANSACTION_PRICE: '757500',
    MAX_TRANSACTION_PRICE: '867500',
    MIN_TRANSACTION_PRICE: '647500'
  }
]

const PieData = [
  {name: 'Only Residential For Sale in Mont Kiara, Kuala Lumpur', value: 408},
  {name: 'Also Have Other Demand', value: 502}
]

// Processing data into a range
transactionPrice.forEach((obj: any) => {
  obj.price = [obj.MAX_TRANSACTION_PRICE, obj.MIN_TRANSACTION_PRICE]
})

PSFMedianData.forEach((obj: any) => {
  obj.price = [obj.MAX_TRANSACTION_PRICE, obj.MIN_TRANSACTION_PRICE]
})

const customizedYAxisTick = (props: any) => {
  const {x, y, payload} = props

  return (
    <g transform={`translate(${x},${y})`}>
      <text
        x={0}
        y={0}
        textAnchor="end"
        alignmentBaseline="middle"
        fontSize="14px"
        fontFamily="Roboto-Medium"
      >
        {nFormatter(payload.value, 3)}
      </text>
    </g>
  )
}

const customizedToolTip = (props: any) => {
  const {payload} = props

  return (
    <>
      {payload && payload.length && (
        <Box
          boxShadow="lg"
          borderRadius={4}
          borderWidth="1px"
          borderColor="grey.400"
          bgColor="white"
          minWidth="150px"
        >
          <Heading
            variant="size12"
            bgColor="grey.100"
            color="grey.500"
            px="12px"
            py="8px"
            borderBottomWidth={1}
            borderBottomColor={'grey.500'}
            borderTopRadius={4}
          >
            {payload[0].payload.TRANSACTION_YEAR}
          </Heading>

          <Box fontSize={'10px'} padding="8px" minH={'50px'} color={'grey.500'}>
            <HStack alignItems={'center'} spacing="1">
              <Text fontSize={'10px'} variant="bold">
                Min:
              </Text>
              <Text fontSize={'10px'}>
                {payload[0].payload.MIN_TRANSACTION_PRICE}
              </Text>
            </HStack>
            <HStack alignItems={'center'} spacing="1">
              <Text fontSize={'10px'} variant="bold">
                Median:
              </Text>
              <Text fontSize={'10px'}>
                {payload[0].payload.MEDIAN_TRANSACTION_PRICE}
              </Text>
            </HStack>
            <HStack alignItems={'center'} spacing="1">
              <Text fontSize={'10px'} variant="bold">
                Max:
              </Text>
              <Text fontSize={'10px'}>
                {payload[0].payload.MAX_TRANSACTION_PRICE}
              </Text>
            </HStack>
          </Box>
        </Box>
      )}
    </>
  )
}
const xAxisProperties = {
  tickLine: false,
  height: 50,
  axisLine: false,
  tickMargin: 25,
  padding: {left: 10, right: 10},
  tick: {fontFamily: 'Roboto-Medium', fontSize: '14px'}
}
const YAxisProperties = {
  axisLine: false,
  tickLine: false,
  tick: customizedYAxisTick
}
const AreaProperties = {
  type: 'monotone',
  stroke: '#E1EFFE',
  fill: '#E1EFFE'
}
const MedianLineProperties = {
  type: 'monotone',
  strokeWidth: 3,
  stroke: '#233876'
}
interface medianDataUnit {
  TRANSACTION_YEAR: string
  MEDIAN_TRANSACTION_PRICE: string
  MAX_TRANSACTION_PRICE: string
  MIN_TRANSACTION_PRICE: string
}
interface MedianTypes {
  data: Array<medianDataUnit>
  width?: number
  height?: number
  showXAxis?: boolean
  showYAxis?: boolean
  showArea?: boolean
  showGrid?: boolean
  showToolTip?: boolean
}
export const MedianChart = ({
  data,
  width = 500,
  height = 500,
  showXAxis = true,
  showYAxis = true,
  showArea = true,
  showGrid = true,
  showToolTip = true
}: MedianTypes) => (
  <ComposedChart data={data} width={width} height={height}>
    {showGrid && <CartesianGrid vertical={false} stroke="#F3F4F6" />}
    {showArea && <Area dataKey="price" {...AreaProperties} />}

    <Line dataKey="MEDIAN_TRANSACTION_PRICE" {...MedianLineProperties} />
    {showXAxis && <XAxis dataKey="TRANSACTION_YEAR" {...xAxisProperties} />}
    {showYAxis && <YAxis {...YAxisProperties} />}
    {showToolTip && <Tooltip content={customizedToolTip} />}
  </ComposedChart>
)
export const MedianChartTransactionPrice = () => (
  <MedianChart data={transactionPrice} />
)

interface ChartDataInterface {
  /**
   * Width of the pie chart
   */
  width?: number
  /**
   * height of the pie chart
   */
  height?: number
  data?: Array<KeyValue>
  colors?: Array<string>
}

export const VantagePieChart = ({
  width = 300,
  height = 300,
  colors
}: ChartDataInterface) => {
  const COLORS = colors || [
    '#2AB8E1',
    '#062472',
    '#00C49F',
    '#FFBB28',
    '#FF8042'
  ]
  const RADIAN = Math.PI / 180
  const renderCustomizedLabel = ({
    cx,
    cy,
    midAngle,
    innerRadius,
    outerRadius,
    percent,
    index
  }: {
    cx: number
    cy: number
    midAngle: number
    innerRadius: number
    outerRadius: number
    percent: number
    index: number
  }) => {
    const radius = innerRadius + (outerRadius - innerRadius) * 0.5
    const x = cx + radius * Math.cos(-midAngle * RADIAN)
    const y = cy + radius * Math.sin(-midAngle * RADIAN)

    return (
      <text
        x={x}
        y={y}
        fill="white"
        textAnchor={x > cx ? 'start' : 'end'}
        dominantBaseline="central"
      >
        {`${(percent * 100).toFixed(0)}%`}
      </text>
    )
  }
  const renderLegend = (props: any) => {
    const {payload} = props

    return (
      <ul style={{display: 'flex'}}>
        {payload.map((entry: any, index: number) => (
          <li
            style={{
              display: 'flex',
              alignItems: 'center',
              marginRight: '16px',
              justifyContent: 'flex-start'
            }}
            key={`item-${index}`}
          >
            <svg
              className="recharts-surface"
              width="8"
              height="8"
              viewBox="0 0 32 32"
              version="1.1"
              style={{
                display: 'inline-block',
                verticalAlign: 'middle',
                marginRight: '5px'
              }}
            >
              <path
                fill={entry.color}
                cx="16"
                cy="16"
                type="circle"
                className="recharts-symbols"
                transform="translate(16, 16)"
                d="M16,0A16,16,0,1,1,-16,0A16,16,0,1,1,16,0"
              />
            </svg>
            <span
              style={{fontSize: '12px', maxWidth: '150px', color: '#111928'}}
            >
              {entry.value}
            </span>
          </li>
        ))}
      </ul>
    )
  }

  return (
    <ResponsiveContainer width={width} height={height}>
      <PieChart
        width={width}
        height={height}
        margin={{top: 0, left: 0, right: 0, bottom: 0}}
      >
        <Pie
          data={PieData}
          labelLine={false}
          label={renderCustomizedLabel}
          outerRadius={'90%'}
          paddingAngle={0.4}
          fill="#8884d8"
          dataKey="value"
          legendType="circle"
        >
          {PieData.map((entry, index) => (
            <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
          ))}
        </Pie>
        <Tooltip />
        <Legend iconSize={8} content={renderLegend} align="left" />
      </PieChart>
    </ResponsiveContainer>
  )
}

export const MedianChartPSF = () => <MedianChart data={PSFMedianData} />
