import { useEffect, useMemo, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Activity, MonitorPlay, Users, Server as ServerIcon, Clock } from '../../../lib/icons'
import { jellyfinClient, getSystemApi, getSessionApi } from '../../../api/jellyfin'
import { Section, SubHeading } from '../_ui'

function useApi() {
  return jellyfinClient.getApi()
}

export function ServerDashboardSection() {
  const api = useApi()
  const [now, setNow] = useState(0)

  useEffect(() => {
    const update = () => setNow(Date.now())
    update()
    const id = window.setInterval(update, 60_000)
    return () => window.clearInterval(id)
  }, [])

  const serverInfo = useQuery({
    queryKey: ['jellyfin', 'system-info'],
    queryFn: async () => {
      if (!api) return null
      const res = await getSystemApi(api).getSystemInfo()
      return res.data
    },
    enabled: !!api,
    refetchInterval: 30_000,
  })

  const sessions = useQuery({
    queryKey: ['jellyfin', 'sessions'],
    queryFn: async () => {
      if (!api) return []
      const res = await getSessionApi(api).getSessions()
      return res.data || []
    },
    enabled: !!api,
    refetchInterval: 10_000,
  })

  const info = serverInfo.data
  const activeSessions = sessions.data?.filter(s => s.NowPlayingItem) || []
  const transcodes = activeSessions.filter(s => s.PlayState?.PlayMethod === 'Transcode')

  const uptime = useMemo(() => {
    if (!now) return null
    const start = (info as { ServerStartTime?: string } | null | undefined)?.ServerStartTime
    if (!start) return null
    const ms = now - new Date(start).getTime()
    const days = Math.floor(ms / 86_400_000)
    const hrs = Math.floor((ms % 86_400_000) / 3_600_000)
    return days > 0 ? `${days}d ${hrs}h` : `${hrs}h`
  }, [info, now])

  return (
    <Section id="server-dashboard" title="Server dashboard" description="Live stats and activity">
      <SubHeading label="Overview" />
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-6">
        <StatCard label="Version" value={info?.Version || '-'} icon={<ServerIcon size={12} className="text-accent" />} />
        <StatCard label="Uptime" value={uptime || '-'} icon={<Clock size={12} className="text-accent" />} />
        <StatCard label="Active streams" value={String(activeSessions.length)} icon={<MonitorPlay size={12} className="text-accent" />} />
        <StatCard label="Transcoding" value={String(transcodes.length)} icon={<Activity size={12} className="text-accent" />} />
      </div>

      {activeSessions.length > 0 && (
        <>
          <SubHeading label="Active sessions" />
          <div className="space-y-2 mb-6">
            {activeSessions.map(s => (
              <div key={s.Id} className="flex items-center gap-3 p-3 rounded-lg bg-elevated/30 ring-1 ring-border">
                <div className="w-8 h-8 rounded-full bg-accent/10 grid place-items-center shrink-0">
                  <Users size={13} className="text-accent" />
                </div>
                <div className="min-w-0 flex-1">
                  <p className="text-[12.5px] text-text-1 font-medium truncate">
                    {s.UserName || 'Unknown'}
                  </p>
                  <p className="text-[11px] text-text-3 truncate">
                    {s.NowPlayingItem?.Name}
                    {s.PlayState?.PlayMethod && (
                      <span className={`ml-1.5 text-[10px] uppercase tracking-wider font-semibold ${
                        s.PlayState.PlayMethod === 'Transcode' ? 'text-warning' : 'text-success'
                      }`}>
                        {s.PlayState.PlayMethod}
                      </span>
                    )}
                  </p>
                </div>
                {s.NowPlayingItem?.RunTimeTicks && s.PlayState?.PositionTicks && (
                  <div className="w-24 shrink-0">
                    <div className="h-1 rounded-full bg-elevated overflow-hidden">
                      <div
                        className="h-full bg-accent"
                        style={{ width: `${Math.min(100, (s.PlayState.PositionTicks / s.NowPlayingItem.RunTimeTicks) * 100)}%` }}
                      />
                    </div>
                  </div>
                )}
              </div>
            ))}
          </div>
        </>
      )}


    </Section>
  )
}

function StatCard({ label, value, icon }: { label: string; value: string; icon: React.ReactNode }) {
  return (
    <div className="rounded-xl p-3 bg-elevated/30 ring-1 ring-border">
      <div className="flex items-center gap-1.5 text-[10px] uppercase tracking-[0.16em] font-semibold text-text-3 mb-2">
        {icon}
        {label}
      </div>
      <p className="font-display text-[20px] font-bold text-text-1 tabular-nums leading-none">{value}</p>
    </div>
  )
}
