'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'

import { useI18n } from '@/components/providers/i18n-provider'
import { useLiveGrid } from '@/components/providers/live-grid-provider'
import { useAppMode } from '@/components/providers/app-mode-provider'
import { LanguageSwitcher } from '@/components/site/language-switcher'
import { CommandPalette } from './command-palette'
import { ModeChip } from './mode-banner'
import { NotificationBell } from './notification-bell'
import { Button } from '@/components/ui/controls'
import { IconSignOut } from '@/components/ui/icons'
import { api } from '@/lib/api/client'
import { cn } from '@/lib/cn'
import { styleForState } from '@/lib/ui/state-styles'

/**
 * The command bar (§5).
 *
 * Everything an operator needs to know without looking away from what they are doing:
 * whether the platform is connected, what the grid is doing, which mode they are in, how
 * much of the data can be trusted, and how many situations are asking for attention. On
 * a wall display this strip is often the only thing read from across the room, so the
 * figures are large, tabular, and never move as digits change.
 */
export function Topbar({
  user,
  sidebarTrigger,
  permissions,
  dataHealth,
}: {
  user: { name: string; nameAr: string; role: string; email: string }
  sidebarTrigger?: React.ReactNode
  permissions: string[]
  /** Mean data confidence across instrumented assets, 0–100 (§32). */
  dataHealth: number | null
}) {
  const { t, locale, mw, n } = useI18n()
  const { snapshot, status } = useLiveGrid()
  const { isSimulated } = useAppMode()
  const [signingOut, setSigningOut] = useState(false)
  const [clock, setClock] = useState<string | null>(null)

  // The wall clock is rendered after mount: the server's second and the browser's second
  // are not the same second, and hydrating a mismatch logs an error on every load.
  useEffect(() => {
    const format = () =>
      new Intl.DateTimeFormat(locale === 'ar' ? 'ar-SA-u-nu-latn' : 'en-GB', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false,
        timeZone: 'Asia/Riyadh',
      }).format(new Date())
    setClock(format())
    const timer = setInterval(() => setClock(format()), 1000)
    return () => clearInterval(timer)
  }, [locale])

  const signOut = async () => {
    setSigningOut(true)
    try {
      await api.post('/api/auth/logout')
    } catch {
      // Even if the revoke call fails the operator still wants to leave; the cookie is
      // cleared server-side on the next valid request and the session expires anyway.
    }
    window.location.assign('/login')
  }

  const state = snapshot ? styleForState(snapshot.state) : null
  const criticalCount = snapshot?.criticalCount ?? 0

  return (
    <header className="nabdh-glass sticky top-0 z-30 flex h-14 items-center gap-3 border-b px-3 sm:px-4">
      {sidebarTrigger}

      {/* Connection, then the three figures that describe the grid itself. */}
      <div className="flex items-center gap-2">
        <span
          className={cn(
            'size-2 rounded-full',
            status === 'live' ? 'bg-brand nabdh-pulse' : status === 'reconnecting' ? 'bg-watch' : 'bg-critical',
          )}
          aria-hidden
        />
        <span className="hidden text-[11px] font-medium text-text-muted sm:inline">
          {status === 'live' ? t('common.live') : t('common.networkError')}
        </span>
      </div>

      <div className="hidden items-center gap-5 lg:flex">
        {snapshot ? (
          <>
            <Readout
              label={t('commandCenter.cards.gridStability')}
              value={n(snapshot.stabilityIndex, { maximumFractionDigits: 1 })}
              className={state?.text}
            />
            <Readout
              label={t('commandCenter.cards.totalLoad')}
              value={mw(snapshot.totalLoadMw)}
              unit={t('common.units.mw')}
            />
            <Readout
              label={t('commandCenter.frequency')}
              value={n(snapshot.frequencyHz, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
              unit={t('common.units.hz')}
            />
            {dataHealth !== null ? (
              <Readout
                label={t('commandBar.dataHealth')}
                value={`${n(dataHealth, { maximumFractionDigits: 0 })}%`}
                className={dataHealth >= 85 ? 'text-normal' : dataHealth >= 65 ? 'text-watch' : 'text-critical'}
              />
            ) : null}
          </>
        ) : null}
      </div>

      <div className="ms-auto flex items-center gap-2">
        {criticalCount > 0 ? (
          <Link
            href="/alerts"
            className="inline-flex items-center gap-1.5 rounded-full border border-critical/40 bg-critical/10 px-2.5 py-0.5 text-[11px] font-semibold text-critical transition-colors hover:bg-critical/16"
          >
            <span aria-hidden className="size-1.5 rounded-full bg-critical nabdh-pulse" />
            {t('commandBar.critical', { count: criticalCount })}
          </Link>
        ) : null}

        <ModeChip />

        {clock ? (
          <span
            className="tnum hidden text-[11px] font-medium text-text-muted md:inline"
            aria-label={t('commandBar.time')}
          >
            {clock}
          </span>
        ) : null}

        <CommandPalette permissions={permissions} />
        <NotificationBell />
        <LanguageSwitcher compact />

        <div className="hidden items-center gap-2 border-s border-border ps-3 sm:flex">
          <div className="text-end">
            <p className="text-xs font-medium text-text">{locale === 'ar' ? user.nameAr : user.name}</p>
            <p className="text-[10px] text-text-faint">{t(`role.${user.role}`)}</p>
          </div>
        </div>

        <Button
          variant="ghost"
          size="sm"
          onClick={signOut}
          loading={signingOut}
          aria-label={t('common.signOut')}
          title={t('common.signOut')}
        >
          <IconSignOut className="size-4" />
        </Button>
      </div>

      {/* Announced to screen readers when values change, without stealing focus. */}
      <span aria-live="polite" aria-atomic="true" className="sr-only">
        {snapshot
          ? `${t('a11y.liveRegion')}: ${mw(snapshot.totalLoadMw)} ${t('common.units.mw')}${
              isSimulated ? ` — ${t('mode.simulation.short')}` : ''
            }`
          : ''}
      </span>
    </header>
  )
}

function Readout({
  label,
  value,
  unit,
  className,
}: {
  label: string
  value: string
  unit?: string
  className?: string
}) {
  return (
    <div className="leading-tight">
      <p className="text-[10px] uppercase tracking-wide text-text-faint">{label}</p>
      <p className={cn('tnum text-sm font-semibold text-text', className)}>
        {value}
        {unit ? <span className="ms-1 text-[10px] font-normal text-text-muted">{unit}</span> : null}
      </p>
    </div>
  )
}
