'use client'

import { useRouter, useSearchParams } from 'next/navigation'

import { useI18n } from '@/components/providers/i18n-provider'
import { TimeSeriesChart } from '@/components/charts/time-series'
import { Segmented } from '@/components/ui/controls'
import { CHART_COLORS } from '@/lib/ui/state-styles'
import type { ForecastPoint } from '@/lib/engine/forecast'

const HORIZONS = [
  { value: '60', key: '1h' },
  { value: '360', key: '6h' },
  { value: '720', key: '12h' },
  { value: '1440', key: '24h' },
  { value: '10080', key: '7d' },
]

/**
 * Load forecast with its uncertainty band.
 *
 * The band is drawn as an explicit series rather than a shaded region behind the line,
 * so it is present in the accessible table too — an interval that only exists as a fill
 * colour is invisible to anyone not looking at the picture.
 */
export function ForecastChart({
  points,
  capacityMw,
  horizonMin,
  showCapacity = true,
}: {
  points: ForecastPoint[]
  capacityMw: number
  horizonMin: number
  showCapacity?: boolean
}) {
  const { t, mw } = useI18n()
  const router = useRouter()
  const searchParams = useSearchParams()

  const setHorizon = (value: string) => {
    const params = new URLSearchParams(searchParams.toString())
    params.set('horizon', value)
    router.push(`?${params.toString()}`)
  }

  const data = points.map((point) => ({
    ts: point.ts,
    expected: point.expectedMw,
    lower: point.lowerMw,
    upper: point.upperMw,
    capacity: showCapacity ? capacityMw : undefined,
  }))

  return (
    <div>
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <Segmented
          ariaLabel={t('forecast.horizon')}
          value={String(horizonMin)}
          onChange={setHorizon}
          size="sm"
          options={HORIZONS.map((horizon) => ({
            value: horizon.value,
            label: t(`forecast.horizons.${horizon.key}`),
          }))}
        />
        <p className="text-[11px] text-text-faint">{t('forecast.bandNote')}</p>
      </div>

      <TimeSeriesChart
        data={data}
        height={300}
        ariaLabel={t('forecast.title')}
        valueFormatter={(value) => `${mw(value)} ${t('common.units.mw')}`}
        series={[
          {
            key: 'upper',
            label: t('forecast.band'),
            color: CHART_COLORS.secondary,
            type: 'line',
            strokeDasharray: '3 5',
          },
          {
            key: 'expected',
            label: t('forecast.expected'),
            color: CHART_COLORS.primary,
            type: 'area',
          },
          {
            key: 'lower',
            label: t('forecast.confidenceInterval'),
            color: CHART_COLORS.secondary,
            type: 'line',
            strokeDasharray: '3 5',
          },
          ...(showCapacity
            ? [
                {
                  key: 'capacity',
                  label: t('forecast.availableCapacity'),
                  color: CHART_COLORS.muted,
                  type: 'line' as const,
                  strokeDasharray: '8 4',
                },
              ]
            : []),
        ]}
      />
    </div>
  )
}

/** Renewable output forecast — same shape, different framing. */
export function RenewableChart({
  points,
  capacityMw,
  label,
  color,
}: {
  points: ForecastPoint[]
  capacityMw: number
  label: string
  color: string
}) {
  const { t, mw } = useI18n()

  const data = points.map((point) => ({
    ts: point.ts,
    expected: point.expectedMw,
    upper: point.upperMw,
    lower: point.lowerMw,
    capacity: capacityMw,
  }))

  return (
    <TimeSeriesChart
      data={data}
      height={230}
      ariaLabel={label}
      valueFormatter={(value) => `${mw(value)} ${t('common.units.mw')}`}
      series={[
        { key: 'upper', label: t('forecast.band'), color, type: 'line', strokeDasharray: '3 5' },
        { key: 'expected', label, color, type: 'area' },
        {
          key: 'lower',
          label: t('forecast.confidenceInterval'),
          color,
          type: 'line',
          strokeDasharray: '3 5',
        },
        {
          key: 'capacity',
          label: t('renewables.installed'),
          color: CHART_COLORS.muted,
          type: 'line',
          strokeDasharray: '8 4',
        },
      ]}
    />
  )
}
