// withHooks
// noPage
import esp from 'esoftplay/esp';
import useSafeState from 'esoftplay/state';

import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibLoading } from 'esoftplay/cache/lib/loading/import';
import { LibUtils } from 'esoftplay/cache/lib/utils/import';
import { MarketAds_perform } from 'esoftplay/cache/market/ads_perform/import';
import { MarketStyle } from 'esoftplay/cache/market/style/import';

import moment from 'esoftplay/moment';
import React, { useEffect } from 'react';
import { Dimensions, ScrollView, Text, View } from 'react-native';
import { LineChart } from "react-native-chart-kit";
import Svg, { Rect, Text as TextSVG } from 'react-native-svg';

moment().locale('id')


export interface MarketAds_chartArgs {

}
export interface MarketAds_chartProps {
  title?: string,
  advert_type: 1 | 2 | 0,
  advert_id?: string
}
export default function m(props: MarketAds_chartProps): any {
  const [data, setData] = useSafeState<any[]>()
  const [error, setError] = useSafeState('')
  const [tooltip, setTooltip] = useSafeState({ x: 0, y: 0, visible: false, value: 0 })
  const [index, setIndex] = useSafeState<number>(0)
  const ads_id = props.advert_id || 0

  const [dateRange, setDateRange] = useSafeState({ date_start: moment().add(-6, 'days').localeFormat('YYYY-MM-DD'), date_end: moment().localeFormat('YYYY-MM-DD') })

  useEffect(() => {
    new LibCurl('advert/ads_chart?advert_type=' + props.advert_type + '&advert_id=' + ads_id + '&date_start=' + dateRange?.date_start + '&date_end=' + dateRange?.date_end, null,
      (res, msg) => {
        setData(res)
      }, (msg) => {
        setError(msg?.message)
      }, 1
    )
  }, [dateRange])


  function getDateRange() {
    const max = moment(dateRange?.date_end).localeFormat('MMMM YYYY')
    const min = moment(dateRange?.date_start).localeFormat('MMMM YYYY')
    let range = ''

    if (max == min) {
      range = max
    } else {
      range = min + " - " + max
    }
    return range
  }


  return (
    <>
      {
        error != '' ? <Text>{error}</Text> : !data ? <LibLoading /> :
          <>
            <MarketAds_perform title={props?.title || esp.lang("market/ads_chart", "header_title")} data={data} date_range={(date_start: string, date_end: string) => { setDateRange({ date_start: date_start, date_end: date_end }) }} index={setIndex} />
            <View style={styleId_Z1fBpYN} >
              <ScrollView horizontal>
                <View style={styleId_28fFha} >
                  <LineChart
                    data={{
                      labels: Object.values(data)?.[index]?.map?.((item: any) => moment(item.ondate).localeFormat('DD')),
                      datasets: [
                        {
                          data: Object.values(data)?.[index]?.map?.((item: any) => Number(item?.total))
                        }
                      ]
                    }}
                    formatYLabel={(y: string) => (index == 2 || index == 3 || index == 6) ? LibUtils.money(y) : LibUtils.number(y)}
                    width={Object.values(data)?.[index]?.length > 7 ? (Dimensions.get("window").width * Object.values(data)?.[index]?.length / 7) : Dimensions.get("window").width}
                    height={200}
                    fromZero
                    decorator={() => (
                      <>
                        {
                          tooltip.visible ?
                            <View>
                              <Svg>
                                <Rect
                                  x={tooltip.x + 5}
                                  y={tooltip.y}
                                  width="40"
                                  height="24"
                                  rx={5}
                                  strokeWidth={0.5}
                                  stroke={MarketStyle.colorPrimaryMarket}
                                  fill="white" />
                                <TextSVG
                                  x={tooltip.x + 25}
                                  y={tooltip.y + 16}
                                  fill="#707070"
                                  fontSize="10"
                                  fontFamily="Arial"
                                  textAnchor="middle">
                                  {tooltip.value}
                                </TextSVG>
                              </Svg>
                            </View>
                            :
                            null
                        }
                      </>
                    )}
                    onDataPointClick={(data) => {
                      let isSamePoint = (tooltip.x === data.x && tooltip.y === data.y)

                      if (isSamePoint) {
                        setTooltip({
                          ...tooltip,
                          value: data.value,
                          visible: !tooltip.visible
                        })
                      } else {
                        setTooltip({ x: data.x, value: data.value, y: data.y, visible: true });
                      }

                    }}
                    chartConfig={{
                      backgroundColor: "#fff",
                      backgroundGradientFrom: "#fff",
                      backgroundGradientTo: "#fff",
                      decimalPlaces: 0, // optional, defaults to 2dp
                      color: (opacity = 1) => `rgb(166, 34, 135, ${opacity})`,
                      labelColor: (opacity = 1) => `rgb(166, 34, 135, ${opacity})`,
                      propsForLabels: { fontSize: 10 },
                      propsForBackgroundLines: { stroke: MarketStyle.colorPrimaryMarket, strokeWidth: 0.3, strokeDasharray: "" },
                      propsForDots: {
                        r: "3",
                        strokeWidth: "2",
                        stroke: MarketStyle.colorPrimaryMarket
                      },
                    }}
                    bezier
                    style={{
                      marginLeft: -20,
                      padding: 10,
                      paddingBottom: 0
                    }}
                  />

                  <Text style={styleId_Zbt3wt}>{getDateRange()}</Text>

                </View>
              </ScrollView>

            </View>
          </>
      }
    </>
  )
}
const styleId_Z1fBpYN: any = { marginTop: 10, paddingVertical: 10, borderWidth: 1, borderColor: '#f5f5f5', borderRadius: 7 }
const styleId_28fFha: any = { paddingBottom: 10 }
const styleId_Zbt3wt: any = { textAlign: 'center', fontFamily: 'Arial', fontSize: 14, fontWeight: 'bold', color: MarketStyle.colorPrimaryMarket }