import { useMemo } from 'react'
import ReactECharts from 'echarts-for-react'

import type { MachineDailyUsageStat } from '../../../../entities/machine/model/types'
import {
  analyticsStateMeta,
  formatAnalyticsDate,
  formatAnalyticsDuration,
  formatAnalyticsPercent,
  secondsToHours,
} from './utils'

type MachineUsageTrendChartProps = {
  stats: MachineDailyUsageStat[]
}

type TrendTooltipParam = {
  dataIndex: number
  marker: string
  seriesName: string
  value: number
}

const fontFamily = 'Montserrat Variable, Montserrat, sans-serif'

export function MachineUsageTrendChart({ stats }: MachineUsageTrendChartProps) {
  const option = useMemo(() => ({
    animation: true,
    animationDuration: 220,
    textStyle: {
      fontFamily,
      fontWeight: 500,
    },
    tooltip: {
      trigger: 'axis',
      borderWidth: 0,
      backgroundColor: '#20263a',
      padding: 12,
      textStyle: {
        color: '#ffffff',
        fontSize: 13,
        fontFamily,
      },
      extraCssText:
        'border-radius: 14px; box-shadow: 0 12px 32px rgba(16, 24, 40, 0.22);',
      formatter: (params: TrendTooltipParam | TrendTooltipParam[]) => {
        const items = Array.isArray(params) ? params : [params]
        const stat = stats[items[0]?.dataIndex ?? 0]

        if (!stat) return ''

        return `
          <div style="min-width:260px;">
            <div style="color:#aeb8cc;font-size:12px;margin-bottom:8px;">
              ${formatAnalyticsDate(`${stat.date}T00:00:00.000Z`)}
            </div>
            <div style="display:grid;gap:6px;">
              <div>${items.find((item) => item.seriesName === 'В движении')?.marker ?? ''} В движении: <strong>${formatAnalyticsDuration(stat.movingSeconds)}</strong></div>
              <div>${items.find((item) => item.seriesName === 'Холостой ход')?.marker ?? ''} Холостой ход: <strong>${formatAnalyticsDuration(stat.engineOnSeconds)}</strong></div>
              <div>${items.find((item) => item.seriesName === 'Простой')?.marker ?? ''} Простой: <strong>${formatAnalyticsDuration(stat.idleSeconds)}</strong></div>
              <div>${items.find((item) => item.seriesName === 'Нет данных')?.marker ?? ''} Нет данных: <strong>${formatAnalyticsDuration(stat.noDataSeconds)}</strong></div>
              <div style="margin-top:4px;color:#ffffff;">КПИ использования: <strong>${formatAnalyticsPercent(stat.utilizationPercent)}</strong></div>
            </div>
          </div>
        `
      },
    },
    legend: {
      top: 0,
      right: 0,
      itemWidth: 10,
      itemHeight: 10,
      textStyle: {
        color: '#738098',
        fontSize: 12,
        fontFamily,
      },
    },
    grid: {
      left: 48,
      right: 54,
      top: 44,
      bottom: 32,
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: stats.map((stat) => formatAnalyticsDate(`${stat.date}T00:00:00.000Z`)),
      axisLabel: {
        color: '#738098',
        fontSize: 12,
        fontFamily,
      },
      axisLine: {
        lineStyle: {
          color: '#dbe2ee',
        },
      },
      axisTick: {
        show: false,
      },
    },
    yAxis: [
      {
        type: 'value',
        name: 'часы',
        nameTextStyle: {
          color: '#8c96aa',
          fontSize: 12,
          fontFamily,
        },
        axisLabel: {
          color: '#738098',
          fontSize: 12,
          fontFamily,
        },
        splitLine: {
          lineStyle: {
            color: '#edf0f5',
          },
        },
      },
      {
        type: 'value',
        name: '%',
        min: 0,
        max: 100,
        nameTextStyle: {
          color: '#8c96aa',
          fontSize: 12,
          fontFamily,
        },
        axisLabel: {
          color: '#738098',
          fontSize: 12,
          fontFamily,
          formatter: '{value}%',
        },
        splitLine: {
          show: false,
        },
      },
    ],
    series: [
      {
        name: 'В движении',
        type: 'bar',
        stack: 'usage',
        barMaxWidth: 34,
        itemStyle: {
          color: analyticsStateMeta.MOVING.color,
          borderRadius: [0, 0, 4, 4],
        },
        data: stats.map((stat) => secondsToHours(stat.movingSeconds)),
      },
      {
        name: 'Холостой ход',
        type: 'bar',
        stack: 'usage',
        barMaxWidth: 34,
        itemStyle: {
          color: analyticsStateMeta.ENGINE_ON.color,
        },
        data: stats.map((stat) => secondsToHours(stat.engineOnSeconds)),
      },
      {
        name: 'Простой',
        type: 'bar',
        stack: 'usage',
        barMaxWidth: 34,
        itemStyle: {
          color: analyticsStateMeta.IDLE.color,
        },
        data: stats.map((stat) => secondsToHours(stat.idleSeconds)),
      },
      {
        name: 'Нет данных',
        type: 'bar',
        stack: 'usage',
        barMaxWidth: 34,
        itemStyle: {
          color: analyticsStateMeta.NO_DATA.color,
          borderRadius: [4, 4, 0, 0],
        },
        data: stats.map((stat) => secondsToHours(stat.noDataSeconds)),
      },
      {
        name: 'КПИ использования',
        type: 'line',
        yAxisIndex: 1,
        smooth: true,
        symbolSize: 7,
        lineStyle: {
          width: 2,
          color: '#031d9a',
        },
        itemStyle: {
          color: '#031d9a',
        },
        data: stats.map((stat) => stat.utilizationPercent),
      },
    ],
  }), [stats])

  if (stats.length === 0) {
    return (
      <div className="machine-chart-empty">
        Нет дневной статистики за выбранный период
      </div>
    )
  }

  return (
    <div className="machine-usage-trend-chart">
      <ReactECharts
        option={option}
        notMerge
        lazyUpdate
        style={{ height: 300 }}
      />
    </div>
  )
}
