import { useEffect, useMemo, useState } from 'react'
import { BarChart3, Clock3, PieChart, TrendingUp } from 'lucide-react'

import { machineAnalyticsService } from '../../../../entities/machine/api/machineAnalyticsService'
import type {
  Machine,
  MachineAnalyticsPeriod,
  MachineDailyUsageStat,
  MachineTelemetryInterval,
  MachineUsageSummary,
} from '../../../../entities/machine/model/types'
import { MachineStateTimelineChart } from './MachineStateTimelineChart'
import { MachineUsageDistributionChart } from './MachineUsageDistributionChart'
import { MachineUsageKpiCards } from './MachineUsageKpiCards'
import { MachineUsageTrendChart } from './MachineUsageTrendChart'

import './MachineChartsTab.scss'

type MachineChartsTabProps = {
  machine: Machine
}

type MachineChartsData = {
  intervals: MachineTelemetryInterval[]
  summary: MachineUsageSummary
  dailyStats: MachineDailyUsageStat[]
}

const periodOptions: Array<{
  value: MachineAnalyticsPeriod
  label: string
}> = [
  {
    value: 'today',
    label: 'Сегодня',
  },
  {
    value: 'shift',
    label: 'Смена',
  },
  {
    value: 'week',
    label: 'Неделя',
  },
  {
    value: 'month',
    label: 'Месяц',
  },
]

function getEmptySummary(
  machineId: number,
  period: MachineAnalyticsPeriod,
): MachineUsageSummary {
  return {
    machineId,
    period,
    movingSeconds: 0,
    engineOnSeconds: 0,
    idleSeconds: 0,
    noDataSeconds: 0,
    totalKnownSeconds: 0,
    utilizationPercent: 0,
  }
}

export function MachineChartsTab({ machine }: MachineChartsTabProps) {
  const [period, setPeriod] = useState<MachineAnalyticsPeriod>('today')
  const [data, setData] = useState<MachineChartsData | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const emptySummary = useMemo(
    () => getEmptySummary(machine.id, period),
    [machine.id, period],
  )
  const summary = data?.summary ?? emptySummary
  const intervals = data?.intervals ?? []
  const dailyStats = data?.dailyStats ?? []

  useEffect(() => {
    let isMounted = true

    async function fetchAnalytics() {
      setIsLoading(true)
      setError(null)

      try {
        const [nextIntervals, nextSummary, nextDailyStats] = await Promise.all([
          machineAnalyticsService.getMachineTelemetryIntervals(machine.id, period),
          machineAnalyticsService.getMachineUsageSummary(machine.id, period),
          machineAnalyticsService.getMachineDailyUsageStats(machine.id, period),
        ])

        if (isMounted) {
          setData({
            intervals: nextIntervals,
            summary: nextSummary,
            dailyStats: nextDailyStats,
          })
        }
      } catch {
        if (isMounted) {
          setError('Не удалось загрузить графики АТТ')
          setData(null)
        }
      } finally {
        if (isMounted) {
          setIsLoading(false)
        }
      }
    }

    fetchAnalytics()

    return () => {
      isMounted = false
    }
  }, [machine.id, period])

  return (
    <section className="machine-charts-tab">
      <div className="machine-charts-toolbar">
        <div>
          <div className="device-card__title">
            <BarChart3 size={18} />
            <h3>Графики работы АТТ</h3>
          </div>
          <p>Аналитика по состояниям машины за выбранный период</p>
        </div>

        <div className="machine-charts-period-control" role="group" aria-label="Период графиков">
          {periodOptions.map((option) => (
            <button
              className={period === option.value ? 'is-active' : ''}
              type="button"
              key={option.value}
              onClick={() => setPeriod(option.value)}
            >
              {option.label}
            </button>
          ))}
        </div>
      </div>

      {isLoading && (
        <div className="machine-charts-loading">
          Загрузка графиков...
        </div>
      )}

      {error ? (
        <div className="machine-page-empty-row">{error}</div>
      ) : (
        <>
          <MachineUsageKpiCards summary={summary} />

          <div className="machine-charts-grid">
            <div className="device-card machine-chart-card machine-chart-card--wide">
              <div className="device-card__header">
                <div className="device-card__title">
                  <Clock3 size={18} />
                  <h3>Мнемосхема состояний</h3>
                </div>
                <p>Цветные интервалы работы одной АТТ на временной шкале</p>
              </div>

              <MachineStateTimelineChart
                intervals={intervals}
                machineName={machine.name}
              />
            </div>

            <div className="device-card machine-chart-card">
              <div className="device-card__header">
                <div className="device-card__title">
                  <PieChart size={18} />
                  <h3>Распределение времени</h3>
                </div>
                <p>Длительность и доля каждого состояния</p>
              </div>

              <MachineUsageDistributionChart summary={summary} />
            </div>

            <div className="device-card machine-chart-card machine-chart-card--wide">
              <div className="device-card__header">
                <div className="device-card__title">
                  <TrendingUp size={18} />
                  <h3>Динамика по дням</h3>
                </div>
                <p>Состав времени и КПИ использования по выбранному периоду</p>
              </div>

              <MachineUsageTrendChart stats={dailyStats} />
            </div>
          </div>
        </>
      )}
    </section>
  )
}
