'use client'

import { useEffect, useState } from 'react'

import { useI18n } from '@/components/providers/i18n-provider'
import { Badge, Panel, PanelBody, PanelHeader } from '@/components/ui/display'
import { Button } from '@/components/ui/controls'
import { cn } from '@/lib/cn'

/**
 * Split future (§24).
 *
 * The same minutes, twice: the grid left alone on one side and the grid with the
 * recommended strategy on the other, both advancing on one clock. The single timeline is
 * the whole idea — two independently scrubbable panels would let a viewer compare minute
 * 15 with minute 40 and conclude nothing.
 */
export interface SplitFrame {
  offsetMin: number
  peakRisk: number
  loadPct: number
  tempC: number
  breached: boolean
  note?: string
  noteAr?: string
}

export function SplitFuture({
  without,
  withNabdh,
  className,
}: {
  without: SplitFrame[]
  withNabdh: SplitFrame[]
  className?: string
}) {
  const { t, locale, n } = useI18n()
  const ar = locale === 'ar'

  const length = Math.min(without.length, withNabdh.length)
  const [index, setIndex] = useState(0)
  const [playing, setPlaying] = useState(false)

  useEffect(() => {
    if (!playing || length === 0) return
    const timer = setInterval(() => {
      setIndex((current) => {
        if (current + 1 >= length) {
          setPlaying(false)
          return current
        }
        return current + 1
      })
    }, 1400)
    return () => clearInterval(timer)
  }, [playing, length])

  if (length === 0) return null

  const left = without[Math.min(index, without.length - 1)]
  const right = withNabdh[Math.min(index, withNabdh.length - 1)]

  const Side = ({
    frame,
    title,
    tone,
  }: {
    frame: SplitFrame
    title: string
    tone: 'critical' | 'normal'
  }) => (
    <div
      className={cn(
        'flex-1 rounded-[--radius-panel] border p-4',
        tone === 'critical' ? 'border-critical/35 bg-critical/6' : 'border-normal/35 bg-normal/6',
      )}
    >
      <p className="text-[10px] uppercase tracking-[0.14em] text-text-faint">{title}</p>
      <p
        className={cn(
          'type-data mt-1',
          tone === 'critical' ? 'text-critical' : 'text-normal',
        )}
      >
        {n(frame.peakRisk, { maximumFractionDigits: 0 })}
        <span className="text-base">%</span>
      </p>
      <dl className="mt-3 space-y-1.5 border-t border-border/60 pt-3 text-[11px]">
        <div className="flex items-baseline justify-between gap-2">
          <dt className="text-text-muted">{t('assets.columns.load')}</dt>
          <dd className="tnum font-medium text-text">{n(frame.loadPct, { maximumFractionDigits: 0 })}%</dd>
        </div>
        <div className="flex items-baseline justify-between gap-2">
          <dt className="text-text-muted">{t('assets.columns.temperature')}</dt>
          <dd className="tnum font-medium text-text">{n(frame.tempC, { maximumFractionDigits: 0 })} °C</dd>
        </div>
      </dl>
      <p className={cn('mt-3 text-[11px] leading-relaxed', frame.breached ? 'text-critical' : 'text-normal')}>
        {frame.note ? (ar ? frame.noteAr ?? frame.note : frame.note) : frame.breached ? t('futures.breaches') : t('futures.noBreach')}
      </p>
    </div>
  )

  return (
    <Panel className={className}>
      <PanelHeader
        title={t('twin.split')}
        subtitle={t('twin.splitHint')}
        action={<Badge tone="accent">{t('futures.estimate')}</Badge>}
      />
      <PanelBody className="space-y-4 pt-0">
        <div className="flex flex-col gap-3 md:flex-row">
          <Side frame={left} title={t('twin.without')} tone="critical" />
          <Side frame={right} title={t('twin.with')} tone="normal" />
        </div>

        <div className="flex flex-wrap items-center justify-between gap-3 border-t border-border/70 pt-3">
          <div className="flex items-center gap-2">
            <Button size="sm" variant={playing ? 'secondary' : 'primary'} onClick={() => setPlaying((c) => !c)}>
              {playing ? t('twin.pause') : t('twin.play')}
            </Button>
            <Button size="sm" variant="ghost" onClick={() => setIndex(0)}>
              {t('twin.rewind')}
            </Button>
          </div>
          <span className="tnum text-[11px] font-medium text-text">
            {left.offsetMin === 0
              ? t('timeMachine.offsets.now')
              : `+${n(left.offsetMin)} ${t('common.minutes')}`}
          </span>
        </div>

        <input
          type="range"
          min={0}
          max={length - 1}
          value={index}
          onChange={(event) => setIndex(Number(event.target.value))}
          aria-label={t('twin.timeline')}
          className="w-full accent-brand"
        />
      </PanelBody>
    </Panel>
  )
}
