import {
  Cpu,
  HardDrive,
  Battery,
  Wifi,
  Thermometer,
  Smartphone,
  Shield,
  Monitor,
  MemoryStick,
  RefreshCw,
} from 'lucide-react'
import { Separator } from '@/components/ui/separator'
import { Badge } from '@/components/ui/badge'
import { ScrollArea } from '@/components/ui/scroll-area'
import { useDeviceInfo } from '../hooks/use-device-info'
import { useDeviceLiveStats } from '../hooks/use-device-live-stats'

interface Props {
  deviceId: string
}

const thermalColor: Record<string, string> = {
  none: 'text-green-400',
  light: 'text-yellow-400',
  moderate: 'text-orange-400',
  severe: 'text-red-400',
  critical: 'text-red-500',
  emergency: 'text-red-600',
  shutdown: 'text-red-700',
}

export function DeviceInfoPanel({ deviceId }: Props) {
  const { info, loading, error } = useDeviceInfo(deviceId)
  const live = useDeviceLiveStats(deviceId)

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full gap-2 text-muted-foreground text-sm">
        <RefreshCw size={14} className="animate-spin" />
        Loading device info…
      </div>
    )
  }

  if (error || !info) {
    return (
      <div className="flex items-center justify-center h-full text-muted-foreground text-sm">
        {error ?? 'No device info available.'}
      </div>
    )
  }

  const usedRam = live && info.totalRamMb > 0
    ? info.totalRamMb - live.availableRamMb
    : null
  const ramPct = usedRam !== null && info.totalRamMb > 0
    ? Math.round((usedRam / info.totalRamMb) * 100)
    : null

  return (
    <ScrollArea className="h-full">
      <div className="p-5 space-y-5">

        {/* Header */}
        <div>
          <h2 className="text-lg font-semibold">{info.model || info.product}</h2>
          <p className="text-sm text-muted-foreground">{info.manufacturer}</p>
          {info.serialNumber && (
            <p className="text-xs text-muted-foreground font-mono mt-0.5">{info.serialNumber}</p>
          )}
        </div>

        <Separator />

        {/* System — static */}
        <Section icon={Smartphone} title="System">
          <Row label="Android" value={
            info.androidVersion
              ? `Android ${info.androidVersion} (SDK ${info.sdkVersion})`
              : '—'
          } />
          <Row label="Security patch" value={info.securityPatch || '—'} />
        </Section>

        <Separator />

        {/* Processor — static */}
        <Section icon={Cpu} title="Processor">
          <Row label="Primary ABI" value={info.abi || '—'} />
          <Row label="Supported ABIs" value={info.supportedAbis || '—'} />
        </Section>

        <Separator />

        {/* Display — static */}
        <Section icon={Monitor} title="Display">
          <Row label="Resolution" value={info.screenResolution || '—'} />
          <Row label="Density" value={info.screenDensity ? `${info.screenDensity} dpi` : '—'} />
        </Section>

        <Separator />

        {/* Memory — total static, available live */}
        <Section icon={MemoryStick} title="Memory">
          <Row label="Total RAM" value={info.totalRamMb > 0 ? `${info.totalRamMb} MB` : '—'} />
          <Row
            label="Available RAM"
            value={live ? `${live.availableRamMb} MB` : '—'}
            live
          />
          {ramPct !== null && (
            <>
              <div className="mt-1 h-1.5 rounded-full bg-muted overflow-hidden">
                <div
                  className="h-full bg-primary rounded-full transition-all duration-500"
                  style={{ width: `${ramPct}%` }}
                />
              </div>
              <p className="text-xs text-muted-foreground">{ramPct}% used</p>
            </>
          )}
        </Section>

        <Separator />

        {/* Storage — total static, available live */}
        <Section icon={HardDrive} title="Storage">
          <Row label="Total" value={info.totalStorageGb || '—'} />
          <Row label="Available" value={live?.availableStorageGb || '—'} live />
        </Section>

        <Separator />

        {/* Battery — fully live */}
        <Section icon={Battery} title="Battery">
          <Row
            label="Level"
            value={
              live && live.batteryLevel > 0 ? (
                <span className={live.batteryLevel < 20 ? 'text-red-400' : ''}>
                  {live.batteryLevel}%
                </span>
              ) : '—'
            }
            live
          />
          <Row
            label="Status"
            value={live?.batteryStatus
              ? <Badge variant="secondary">{live.batteryStatus}</Badge>
              : '—'
            }
            live
          />
        </Section>

        <Separator />

        {/* Thermal — fully live */}
        <Section icon={Thermometer} title="Thermal">
          <Row
            label="Status"
            value={
              live?.thermalStatus ? (
                <span className={thermalColor[live.thermalStatus] ?? ''}>
                  {live.thermalStatus}
                </span>
              ) : '—'
            }
            live
          />
        </Section>

        <Separator />

        {/* Network — IP is live */}
        <Section icon={Wifi} title="Network">
          <Row label="IP address" value={live?.ipAddress || '—'} mono live />
        </Section>

        <Separator />

        {/* Build — static */}
        <Section icon={Shield} title="Build">
          <Row label="Fingerprint" value={info.buildFingerprint || '—'} mono />
        </Section>

      </div>
    </ScrollArea>
  )
}

function Section({
  icon: Icon,
  title,
  children,
}: {
  icon: React.ElementType
  title: string
  children: React.ReactNode
}) {
  return (
    <div className="space-y-2">
      <div className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground uppercase tracking-wide">
        <Icon size={12} />
        {title}
      </div>
      <div className="space-y-1.5">{children}</div>
    </div>
  )
}

function Row({
  label,
  value,
  mono,
  live,
}: {
  label: string
  value: React.ReactNode
  mono?: boolean
  live?: boolean
}) {
  return (
    <div className="flex items-start justify-between gap-4 text-sm">
      <span className="text-muted-foreground shrink-0 flex items-center gap-1">
        {live && (
          <span className="inline-block w-1.5 h-1.5 rounded-full bg-green-500 animate-pulse" />
        )}
        {label}
      </span>
      <span className={['text-right break-all', mono ? 'font-mono text-xs' : ''].join(' ')}>
        {value ?? '—'}
      </span>
    </div>
  )
}
