import { Link } from 'react-router'
import { useQuery } from '@tanstack/react-query'
import {
  IconArrowRight,
  IconBooks,
  IconClock,
  IconDatabase,
  IconDeviceDesktopAnalytics,
  IconDownload,
  IconServer2,
} from '@tabler/icons-react'
import { api, formatBytes, type NodeStatus } from '../lib/api'
import { useLang } from '../i18n/LanguageContext'
import type { TranslationKey } from '../i18n/translations'
import { ModuleCard } from '../components/ModuleCard'
import { StatusBadge } from '../components/StatusBadge'

function ReadinessRing({ value }: { value: number }) {
  const radius = 47
  const circumference = 2 * Math.PI * radius
  const offset = circumference - (value / 100) * circumference
  const color =
    value >= 75
      ? 'var(--color-arka-online)'
      : value >= 50
        ? 'var(--color-arka-degraded)'
        : 'var(--color-arka-offline)'

  return (
    <div className="relative h-32 w-32 flex-none" data-testid="node-readiness">
      <svg width="128" height="128" viewBox="0 0 128 128" className="-rotate-90">
        <circle cx="64" cy="64" r={radius} fill="none" stroke="rgba(255,255,255,.08)" strokeWidth="9" />
        <circle
          cx="64"
          cy="64"
          r={radius}
          fill="none"
          stroke={color}
          strokeWidth="9"
          strokeLinecap="round"
          strokeDasharray={circumference}
          strokeDashoffset={offset}
          style={{ transition: 'stroke-dashoffset .8s cubic-bezier(.2,.8,.2,1)' }}
        />
      </svg>
      <div className="absolute inset-0 flex flex-col items-center justify-center">
        <span className="text-3xl font-bold tracking-tight text-white">{value}%</span>
        <span className="mt-0.5 text-[9px] uppercase tracking-[0.18em] text-arka-muted">ready</span>
      </div>
    </div>
  )
}

function duration(seconds: number, lang: 'lt' | 'en'): string {
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  if (days > 0) return `${days}${lang === 'lt' ? ' d.' : 'd'} ${hours}${lang === 'lt' ? ' val.' : 'h'}`
  if (hours > 0) return `${hours}${lang === 'lt' ? ' val.' : 'h'} ${minutes}${lang === 'lt' ? ' min.' : 'm'}`
  return `${Math.max(1, minutes)} ${lang === 'lt' ? 'min.' : 'min'}`
}

export function Dashboard() {
  const { t, lang } = useLang()
  const { data, isLoading, isError } = useQuery({
    queryKey: ['status'],
    queryFn: api.getStatus,
    staleTime: 0,
    refetchInterval: 5000,
  })

  const copy = lang === 'lt'
    ? {
        eyebrow: 'AUTONOMINIO MAZGO KONTROLĖ',
        hero: 'Svarbiausi ištekliai lieka pasiekiami.',
        body: 'Vietinis žinių, žemėlapių ir sprendimų mazgas, sukurtas veikti tada, kai išorinis tinklas nepasiekiamas.',
        knowledge: 'Atidaryti žinias',
        content: 'Valdyti turinį',
        telemetry: 'Gyva mazgo telemetrija',
        capabilities: 'Pajėgumai',
        next: 'Kitas pasirengimo veiksmas',
        nextBody: 'Atsisiųskite bent vieną vietinį žinyną ir žemėlapį. Taip Žmogaus lygmens funkcijos išliks naudingos visiškai be interneto.',
        openDownloads: 'Atidaryti atsisiuntimus',
        memory: 'Atminties apkrova',
        storage: 'Disko panaudojimas',
        uptime: 'Hosto veikimo laikas',
        process: 'A.R.K.A. procesas',
      }
    : {
        eyebrow: 'AUTONOMOUS NODE CONTROL',
        hero: 'Critical resources stay within reach.',
        body: 'A local knowledge, mapping and decision-support node built for the moment the outside network disappears.',
        knowledge: 'Open knowledge',
        content: 'Manage content',
        telemetry: 'Live node telemetry',
        capabilities: 'Capabilities',
        next: 'Next readiness action',
        nextBody: 'Download at least one local reference archive and map. This keeps the Human layer useful with no internet at all.',
        openDownloads: 'Open downloads',
        memory: 'Memory load',
        storage: 'Disk utilisation',
        uptime: 'Host uptime',
        process: 'A.R.K.A. process',
      }

  if (isLoading) {
    return <div className="h-80 animate-pulse rounded-3xl border border-arka-border bg-arka-surface" />
  }

  if (isError || !data) {
    return (
      <div className="rounded-2xl border border-arka-offline/30 bg-arka-offline/10 p-6 text-arka-offline">
        {lang === 'lt'
          ? 'Nepavyko pasiekti vietinio mazgo API. Patikrinkite, ar backend procesas paleistas.'
          : 'The local node API is unreachable. Check that the backend process is running.'}
      </div>
    )
  }

  const memoryUsed = data.node.memory.totalBytes - data.node.memory.freeBytes
  const storageUsed = data.node.storage.totalBytes - data.node.storage.freeBytes

  return (
    <div className="space-y-8" data-testid="command-center">
      <section className="command-hero overflow-hidden rounded-[1.75rem] border border-arka-border p-5 sm:p-7 lg:p-9">
        <div className="relative z-10 grid items-center gap-7 lg:grid-cols-[1fr_auto]">
          <div className="max-w-3xl">
            <div className="mb-4 flex flex-wrap items-center gap-3">
              <span className="text-[10px] font-bold uppercase tracking-[0.24em] text-arka-accent">{copy.eyebrow}</span>
              <StatusBadge status={data.status} />
              <span className="rounded-full border border-white/10 bg-white/5 px-2.5 py-1 text-[10px] uppercase tracking-[0.13em] text-arka-muted">
                {data.node.name} · v{data.node.version}
              </span>
            </div>
            <h1 className="max-w-2xl text-3xl font-semibold leading-[1.08] tracking-[-0.035em] text-white sm:text-4xl lg:text-[3.25rem]">
              {copy.hero}
            </h1>
            <p className="mt-4 max-w-2xl text-sm leading-6 text-arka-muted sm:text-base">{copy.body}</p>
            <div className="mt-6 flex flex-wrap gap-3">
              <Link to="/knowledge" className="inline-flex items-center gap-2 rounded-xl bg-arka-accent px-4 py-2.5 text-sm font-semibold text-arka-bg transition hover:brightness-110">
                <IconBooks size={17} /> {copy.knowledge}
              </Link>
              <Link to="/downloads" className="inline-flex items-center gap-2 rounded-xl border border-white/12 bg-white/5 px-4 py-2.5 text-sm font-medium text-white transition hover:border-arka-accent/40 hover:bg-white/8">
                <IconDownload size={17} /> {copy.content}
              </Link>
            </div>
          </div>
          <div className="flex items-center gap-5 rounded-2xl border border-white/8 bg-black/20 p-4 backdrop-blur-sm sm:p-5">
            <ReadinessRing value={data.readiness} />
            <div className="grid gap-2 text-xs">
              <div><span className="text-2xl font-semibold text-arka-online">{data.summary.online}</span><span className="ml-2 text-arka-muted">{t('status.online')}</span></div>
              <div><span className="text-2xl font-semibold text-arka-degraded">{data.summary.degraded}</span><span className="ml-2 text-arka-muted">{t('status.degraded')}</span></div>
              <div><span className="text-2xl font-semibold text-arka-muted">{data.summary.not_installed}</span><span className="ml-2 text-arka-muted">{t('status.not_installed')}</span></div>
            </div>
          </div>
        </div>
      </section>

      <section>
        <div className="mb-4 flex items-end justify-between gap-4">
          <div>
            <div className="text-[10px] font-semibold uppercase tracking-[0.2em] text-arka-accent">SYSTEM</div>
            <h2 className="mt-1 text-xl font-semibold text-white">{copy.telemetry}</h2>
          </div>
          <div className="hidden text-right text-[10px] uppercase tracking-[0.12em] text-arka-muted sm:block" data-testid="node-status">
            {new Date(data.node.updatedAt).toLocaleTimeString(lang === 'lt' ? 'lt-LT' : 'en-GB')}
            <span className="ml-2 text-arka-online">● LIVE</span>
          </div>
        </div>
        <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
          <TelemetryCard icon={<IconDeviceDesktopAnalytics size={20} />} label={copy.memory} value={`${data.node.memory.usedPercent}%`} detail={`${formatBytes(memoryUsed)} / ${formatBytes(data.node.memory.totalBytes)}`} percent={data.node.memory.usedPercent} />
          <TelemetryCard icon={<IconDatabase size={20} />} label={copy.storage} value={`${data.node.storage.usedPercent}%`} detail={`${formatBytes(storageUsed)} / ${formatBytes(data.node.storage.totalBytes)}`} percent={data.node.storage.usedPercent} />
          <TelemetryCard icon={<IconClock size={20} />} label={copy.uptime} value={duration(data.node.uptimeSeconds, lang)} detail={data.node.hostname} />
          <TelemetryCard icon={<IconServer2 size={20} />} label={copy.process} value={duration(data.node.processUptimeSeconds, lang)} detail="Node.js · local-only" />
        </div>
      </section>

      <section>
        <div className="mb-4">
          <div className="text-[10px] font-semibold uppercase tracking-[0.2em] text-arka-accent">TCP MODEL</div>
          <h2 className="mt-1 text-xl font-semibold text-white">{t('dashboard.layers')}</h2>
        </div>
        <div className="grid gap-3 sm:grid-cols-3">
          {data.layers.map((layer) => <LayerTile key={layer.layer} summary={layer} />)}
        </div>
      </section>

      <section>
        <div className="mb-4 flex items-center justify-between">
          <div>
            <div className="text-[10px] font-semibold uppercase tracking-[0.2em] text-arka-accent">MODULES</div>
            <h2 className="mt-1 text-xl font-semibold text-white">{copy.capabilities}</h2>
          </div>
        </div>
        <div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
          {data.modules.map((module) => <ModuleCard key={module.id} module={module} />)}
        </div>
      </section>

      <section className="flex flex-col gap-5 rounded-2xl border border-arka-accent/20 bg-arka-accent/6 p-5 sm:flex-row sm:items-center sm:justify-between sm:p-6">
        <div>
          <div className="text-xs font-semibold uppercase tracking-[0.16em] text-arka-accent">{copy.next}</div>
          <p className="mt-2 max-w-3xl text-sm leading-6 text-arka-muted">{copy.nextBody}</p>
        </div>
        <Link to="/downloads" className="inline-flex flex-none items-center gap-2 text-sm font-semibold text-arka-accent hover:text-white">
          {copy.openDownloads} <IconArrowRight size={17} />
        </Link>
      </section>
    </div>
  )
}

function TelemetryCard({ icon, label, value, detail, percent }: { icon: React.ReactNode; label: string; value: string; detail: string; percent?: number }) {
  return (
    <article className="telemetry-card rounded-2xl border border-arka-border bg-arka-surface p-4">
      <div className="flex items-start justify-between">
        <div className="flex h-9 w-9 items-center justify-center rounded-lg border border-arka-border bg-arka-surface-2 text-arka-accent">{icon}</div>
        <span className="text-[9px] font-semibold uppercase tracking-[0.16em] text-arka-online">live</span>
      </div>
      <div className="mt-5 text-[11px] font-medium uppercase tracking-[0.12em] text-arka-muted">{label}</div>
      <div className="mt-1 text-2xl font-semibold tracking-tight text-white">{value}</div>
      <div className="mt-1 truncate text-[11px] text-arka-muted">{detail}</div>
      {percent !== undefined && (
        <div className="mt-3 h-1 overflow-hidden rounded-full bg-white/7"><div className="h-full rounded-full bg-arka-accent" style={{ width: `${Math.min(100, percent)}%` }} /></div>
      )}
    </article>
  )
}

function LayerTile({ summary }: { summary: NodeStatus['layers'][number] }) {
  const { t } = useLang()
  const key = `layer.${summary.layer}` as TranslationKey
  const healthy = summary.total > 0 && summary.online === summary.total
  const progress = summary.total > 0 ? Math.round((summary.online / summary.total) * 100) : 0

  return (
    <article className="rounded-2xl border border-arka-border bg-arka-surface p-4">
      <div className="flex items-center justify-between">
        <h3 className="text-sm font-semibold text-white">{t(key)}</h3>
        <span className={`text-xs font-semibold ${healthy ? 'text-arka-online' : 'text-arka-degraded'}`}>{summary.online}/{summary.total}</span>
      </div>
      <div className="mt-4 h-1.5 overflow-hidden rounded-full bg-white/7"><div className={`h-full rounded-full ${healthy ? 'bg-arka-online' : 'bg-arka-degraded'}`} style={{ width: `${progress}%` }} /></div>
    </article>
  )
}
