import { useEffect, useMemo, useRef, useState } from 'react'
import Taro, { useDidShow } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { ConfigProvider, DatePicker } from '@nutui/nutui-react-taro'
import { EChart } from 'echarts-taro3-react'
import dayjs from 'dayjs'

type RangePreset = '近6个月' | '近12个月'
type TimeMode = '当日' | '当月' | '当年'

const formatYmd = (d?: Date | null) => {
  if (!d) return ''
  return dayjs(d).format('YYYY-MM-DD')
}

const makeMonthLabels = (count: number) => {
  const now = dayjs()
  const arr: string[] = []
  for (let i = count - 1; i >= 0; i--) {
    arr.push(`${now.subtract(i, 'month').month() + 1}月`)
  }
  return arr
}

const buildLineOption = (months: string[], series: { name: string; data: number[]; color: string }[]) => {
  return {
    grid: { left: 36, right: 18, top: 28, bottom: 32, containLabel: false },
    tooltip: { trigger: 'axis' },
    xAxis: {
      type: 'category',
      data: months,
      boundaryGap: false,
      axisLine: { lineStyle: { color: '#e5e7eb' } },
      axisTick: { show: false },
      axisLabel: { color: '#6b7280', fontSize: 10 }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 600000,
      splitNumber: 3,
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: {
        color: '#6b7280',
        fontSize: 10,
        formatter: (v: number) => (v >= 10000 ? `${Math.round(v / 10000)}w` : `${v}`)
      },
      splitLine: { lineStyle: { color: '#f3f4f6' } }
    },
    series: series.map(s => ({
      name: s.name,
      type: 'line',
      data: s.data,
      symbol: 'circle',
      symbolSize: 6,
      showSymbol: true,
      lineStyle: { width: 2, color: s.color },
      itemStyle: { color: s.color },
      label: { show: true, color: s.color, fontSize: 10, position: 'top' }
    }))
  }
}

function Annotation({
  num,
  text,
  className
}: {
  num: 1 | 2 | 3 | 4
  text: string
  className: string
}) {
  return (
    <View className={`absolute ${className} bg-yellow-200 border border-yellow-300 rounded-lg px-2 py-2 text-xs text-gray-900`}>
      <View className="flex items-start gap-2">
        <View className="w-5 h-5 rounded-full bg-yellow-300 flex items-center justify-center text-xs font-semibold text-gray-900">
          <Text>{num}</Text>
        </View>
        <View className="flex-1">
          <Text>{text}</Text>
        </View>
      </View>
    </View>
  )
}

export default function CreditDataPage() {

  const [rangePreset, setRangePreset] = useState<RangePreset>('近6个月')
  const months = useMemo(() => makeMonthLabels(rangePreset === '近6个月' ? 6 : 12), [rangePreset])

  const [timeMode, setTimeMode] = useState<TimeMode>('当月')
  const [picking, setPicking] = useState<'start' | 'end'>('start')
  const [datePickerVisible, setDatePickerVisible] = useState(false)
  const [startDate, setStartDate] = useState<Date | null>(null)
  const [endDate, setEndDate] = useState<Date | null>(null)

  const chartRef = useRef<any>()

  const chartOption = useMemo(() => {
    const len = months.length
    const scale = rangePreset === '近6个月' ? 1 : 0.9

    // 近似还原示意图：5月附近峰值，最后一个月回落。
    const mk = (base: number, peak: number) => {
      const out: number[] = []
      for (let i = 0; i < len; i++) {
        const t = i / Math.max(1, len - 1)
        const wave = Math.sin(t * Math.PI) * peak
        out.push(Math.round((base + wave) * scale))
      }
      if (out.length) out[out.length - 1] = Math.round(out[out.length - 1] * 0.55)
      return out
    }

    const series = [
      { name: '订单完成情况', data: mk(180000, 220000), color: '#ec4899' },
      { name: '回款金额情况', data: mk(120000, 160000), color: '#22c55e' },
      { name: '提成获取情况', data: mk(90000, 120000), color: '#3b82f6' }
    ]
    return buildLineOption(months, series)
  }, [months, rangePreset])

  useEffect(() => {
    if (chartRef.current) chartRef.current.refresh(chartOption)
  }, [chartOption])

  useDidShow(() => {
    if (chartRef.current) chartRef.current.refresh(chartOption)
  })

  const pickRangePreset = async () => {
    try {
      const options: RangePreset[] = ['近6个月', '近12个月']
      const res = await Taro.showActionSheet({ itemList: options })
      const next = options[res.tapIndex]
      if (next) setRangePreset(next)
    } catch (e) {
      const msg = String((e as any)?.errMsg || (e as any)?.message || e || '')
      if (msg.includes('cancel')) return
      console.error('选择时间范围失败:', e)
    }
  }

  const followSteps = useMemo(() => {
    return [
      { name: '跟进第一步', count: 50 },
      { name: '跟进第二步', count: 20 },
      { name: '跟进第三步', count: 20 },
      { name: '跟进第四步', count: 20 },
      { name: '跟进第五步', count: 20 },
      { name: '跟进第六步', count: 20 }
    ]
  }, [])

  return (
    <View className="bg-pink-50 min-h-screen">
      <ConfigProvider>
        <View className="max-w-md mx-auto px-4 pb-24">
          <View className="bg-white rounded-xl border border-pink-100 p-4 relative">
            <View className="flex items-center justify-between">
              <Text className="text-sm font-semibold text-gray-900">数据查询统计</Text>
              <View
                className="text-xs text-gray-600 border border-gray-200 rounded-full px-3 py-1"
                onClick={pickRangePreset}
              >
                <Text>{rangePreset}</Text>
              </View>
            </View>

            <View className="mt-3 relative" style={{ height: '260px' }}>
              <EChart ref={chartRef} canvasId="credit-data-line-canvas" />

              <Annotation
                num={1}
                text="编号1：订单完成情况（粉色折线）"
                className="right-2 top-2 w-40"
              />
              <Annotation
                num={2}
                text="编号2：回款金额情况（绿色折线）"
                className="right-2 top-24 w-40"
              />
              <Annotation
                num={3}
                text="编号3：提成获取情况（蓝色折线）"
                className="right-2 top-44 w-40"
              />
            </View>
          </View>

          <View className="mt-4 bg-white rounded-xl border border-pink-100 p-4 relative">
            <View className="flex items-center justify-between">
              <Text className="text-sm font-semibold text-gray-900">跟进统计数据</Text>
              <View className="flex items-center gap-2 text-xs">
                {(['当日', '当月', '当年'] as TimeMode[]).map(m => (
                  <View
                    key={m}
                    className={`px-3 py-1 rounded-full border ${timeMode === m ? 'bg-pink-500 border-pink-500' : 'bg-white border-gray-200'}`}
                    onClick={() => setTimeMode(m)}
                  >
                    <Text className={timeMode === m ? 'text-white' : 'text-gray-700'}>{m}</Text>
                  </View>
                ))}
              </View>
            </View>

            <View className="mt-3 flex items-center gap-3">
              <View
                className="flex-1 border border-gray-200 rounded-lg px-3 py-2 text-xs text-gray-600"
                onClick={() => {
                  setPicking('start')
                  setDatePickerVisible(true)
                }}
              >
                <Text>{formatYmd(startDate) || '请选择开始时间'}</Text>
              </View>
              <View
                className="flex-1 border border-gray-200 rounded-lg px-3 py-2 text-xs text-gray-600"
                onClick={() => {
                  setPicking('end')
                  setDatePickerVisible(true)
                }}
              >
                <Text>{formatYmd(endDate) || '请选择结束时间'}</Text>
              </View>
            </View>

            <View className="mt-4">
              {followSteps.map(s => (
                <View key={s.name} className="flex items-center justify-between py-2 border-b border-gray-50">
                  <Text className="text-sm text-gray-800">{s.name}</Text>
                  <Text className="text-sm text-gray-600">{s.count}个</Text>
                </View>
              ))}
            </View>

            <Annotation
              num={4}
              text="编号4：跟进日期选择（开始/结束）会导致统计数量变化"
              className="right-2 top-24 w-44"
            />
          </View>
        </View>

        <DatePicker
          visible={datePickerVisible}
          title={picking === 'start' ? '选择开始时间' : '选择结束时间'}
          type="date"
          value={(picking === 'start' ? startDate : endDate) || new Date()}
          startDate={dayjs('2020-01-01').toDate()}
          endDate={dayjs('2035-12-31').toDate()}
          onClose={() => setDatePickerVisible(false)}
          onCancel={() => setDatePickerVisible(false)}
          onConfirm={(_options, selectedValue) => {
            const [y, m, d] = (selectedValue || []).map(v => Number(v))
            const next = new Date(y, (m || 1) - 1, d || 1, 0, 0, 0)

            if (picking === 'start') {
              setStartDate(next)
              if (endDate && dayjs(endDate).isBefore(next, 'day')) setEndDate(null)
            } else {
              setEndDate(next)
              if (startDate && dayjs(next).isBefore(startDate, 'day')) setStartDate(null)
            }
            setDatePickerVisible(false)
          }}
        />
      </ConfigProvider>
    </View>
  )
}
