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

import type { MachineUsageSummary } from '../../../../entities/machine/model/types'
import {
  analyticsStateMeta,
  formatAnalyticsDuration,
  getSummaryTotalSeconds,
} from './utils'

type MachineUsageDistributionChartProps = {
  summary: MachineUsageSummary
}

type DistributionTooltipParam = {
  name: string
  value: number
  percent?: number
}

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

export function MachineUsageDistributionChart({
  summary,
}: MachineUsageDistributionChartProps) {
  const items = useMemo(() => [
    {
      key: 'moving',
      state: 'MOVING' as const,
      value: summary.movingSeconds,
    },
    {
      key: 'engine-on',
      state: 'ENGINE_ON' as const,
      value: summary.engineOnSeconds,
    },
    {
      key: 'idle',
      state: 'IDLE' as const,
      value: summary.idleSeconds,
    },
    {
      key: 'no-data',
      state: 'NO_DATA' as const,
      value: summary.noDataSeconds,
    },
  ], [summary])
  const totalSeconds = getSummaryTotalSeconds(summary)
  const option = useMemo(() => ({
    animation: true,
    animationDuration: 220,
    textStyle: {
      fontFamily,
      fontWeight: 500,
    },
    tooltip: {
      trigger: 'item',
      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: DistributionTooltipParam) => (
        `${params.name}<br/><strong>${formatAnalyticsDuration(Number(params.value))}</strong> · ${Math.round(params.percent ?? 0)}%`
      ),
    },
    series: [
      {
        name: 'Распределение времени',
        type: 'pie',
        radius: ['58%', '76%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: true,
        label: {
          show: false,
        },
        labelLine: {
          show: false,
        },
        data: items.map((item) => ({
          name: analyticsStateMeta[item.state].label,
          value: item.value,
          itemStyle: {
            color: analyticsStateMeta[item.state].color,
          },
        })),
      },
    ],
  }), [items])

  if (totalSeconds <= 0) {
    return (
      <div className="machine-chart-empty">
        Нет данных для распределения времени
      </div>
    )
  }

  return (
    <div className="machine-distribution-chart">
      <ReactECharts
        option={option}
        notMerge
        lazyUpdate
        style={{ height: 220 }}
      />

      <div className="machine-distribution-list">
        {items.map((item) => {
          const stateMeta = analyticsStateMeta[item.state]
          const percent = totalSeconds > 0
            ? Math.round((item.value / totalSeconds) * 100)
            : 0

          return (
            <div className="machine-distribution-item" key={item.key}>
              <span
                className="machine-distribution-item__dot"
                style={{ backgroundColor: stateMeta.color }}
              />
              <span>{stateMeta.label}</span>
              <strong>{formatAnalyticsDuration(item.value)}</strong>
              <em>{percent}%</em>
            </div>
          )
        })}
      </div>
    </div>
  )
}
