import { useEffect, useState } from 'react'
import { apiRequest, getMonitorProcesses, getMonitorNetwork } from '../api/client'
import { Cpu, HardDrive, MemoryStick, Activity, Network } from 'lucide-react'

interface SystemStats {
  cpu_percent: number
  memory_percent: number
  memory_used_mb: number
  memory_total_mb: number
  disk_percent: number
  disk_used_gb: number
  disk_total_gb: number
}

interface ProcessInfo {
  pid: number
  name: string
  username: string
  cpu_percent: number
  memory_percent: number
  status: string
}

interface NetworkStats {
  bytes_sent_mb: number
  bytes_recv_mb: number
}

export function MonitorPage() {
  const [stats, setStats] = useState<SystemStats | null>(null)
  const [processes, setProcesses] = useState<ProcessInfo[]>([])
  const [network, setNetwork] = useState<NetworkStats | null>(null)
  const [error, setError] = useState('')

  useEffect(() => {
    const fetchStats = () => {
      apiRequest<SystemStats>('/monitor/system')
        .then(setStats)
        .catch((err) => setError(err.message))
    }
    const fetchProcesses = () => {
      getMonitorProcesses(50)
        .then((d) => setProcesses(d.processes))
        .catch(() => setProcesses([]))
    }
    const fetchNetwork = () => {
      getMonitorNetwork()
        .then(setNetwork)
        .catch(() => setNetwork(null))
    }
    fetchStats()
    fetchProcesses()
    fetchNetwork()
    const interval = setInterval(() => {
      fetchStats()
      fetchProcesses()
      fetchNetwork()
    }, 3000)
    return () => clearInterval(interval)
  }, [])

  if (error) return <div className="p-4 rounded bg-red-100 text-red-700">{error}</div>
  if (!stats) return <div className="text-gray-500">Loading...</div>

  return (
    <div>
      <h1 className="text-2xl font-bold mb-6 text-gray-800 dark:text-white">Monitor</h1>
      <p className="text-sm text-gray-500 mb-4">Refreshes every 3 seconds</p>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <StatCard
          icon={<Cpu className="w-10 h-10" />}
          title="CPU"
          value={`${stats.cpu_percent}%`}
          subtitle="Usage"
          percent={stats.cpu_percent}
        />
        <StatCard
          icon={<MemoryStick className="w-10 h-10" />}
          title="Memory"
          value={`${stats.memory_used_mb} / ${stats.memory_total_mb} MB`}
          subtitle={`${stats.memory_percent}% used`}
          percent={stats.memory_percent}
        />
        <StatCard
          icon={<HardDrive className="w-10 h-10" />}
          title="Disk"
          value={`${stats.disk_used_gb} / ${stats.disk_total_gb} GB`}
          subtitle={`${stats.disk_percent}% used`}
          percent={stats.disk_percent}
        />
      </div>

      {network && (
        <div className="mt-6 p-4 bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-200 dark:border-gray-700">
          <div className="flex items-center gap-2 mb-3 text-gray-800 dark:text-white">
            <Network className="w-5 h-5" />
            <span className="font-medium">Network I/O</span>
          </div>
          <div className="grid grid-cols-2 gap-4 text-sm">
            <div>
              <span className="text-gray-500">Sent</span>
              <p className="font-mono font-medium">{network.bytes_sent_mb} MB</p>
            </div>
            <div>
              <span className="text-gray-500">Received</span>
              <p className="font-mono font-medium">{network.bytes_recv_mb} MB</p>
            </div>
          </div>
        </div>
      )}

      <div className="mt-6 bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden border border-gray-200 dark:border-gray-700">
        <div className="flex items-center gap-2 px-4 py-3 border-b border-gray-200 dark:border-gray-700">
          <Cpu className="w-5 h-5" />
          <span className="font-medium text-gray-800 dark:text-white">Top Processes (by CPU)</span>
        </div>
        <div className="max-h-80 overflow-y-auto">
          <table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
            <thead className="bg-gray-50 dark:bg-gray-700 sticky top-0">
              <tr>
                <th className="px-4 py-2 text-left text-xs font-medium text-gray-700 dark:text-gray-300">PID</th>
                <th className="px-4 py-2 text-left text-xs font-medium text-gray-700 dark:text-gray-300">Name</th>
                <th className="px-4 py-2 text-left text-xs font-medium text-gray-700 dark:text-gray-300">User</th>
                <th className="px-4 py-2 text-right text-xs font-medium text-gray-700 dark:text-gray-300">CPU %</th>
                <th className="px-4 py-2 text-right text-xs font-medium text-gray-700 dark:text-gray-300">Mem %</th>
                <th className="px-4 py-2 text-left text-xs font-medium text-gray-700 dark:text-gray-300">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-200 dark:divide-gray-700">
              {processes.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-4 py-4 text-center text-gray-500 text-sm">No process data</td>
                </tr>
              ) : (
                processes.map((p) => (
                  <tr key={p.pid} className="text-sm">
                    <td className="px-4 py-1.5 font-mono text-gray-700 dark:text-gray-300">{p.pid}</td>
                    <td className="px-4 py-1.5 text-gray-900 dark:text-white truncate max-w-[120px]" title={p.name}>{p.name}</td>
                    <td className="px-4 py-1.5 text-gray-600 dark:text-gray-400">{p.username}</td>
                    <td className="px-4 py-1.5 text-right font-mono">{p.cpu_percent}%</td>
                    <td className="px-4 py-1.5 text-right font-mono">{p.memory_percent}%</td>
                    <td className="px-4 py-1.5 text-gray-500 text-xs">{p.status}</td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      <div className="mt-6 p-4 bg-amber-50 dark:bg-amber-900/20 rounded-lg border border-amber-200 dark:border-amber-800">
        <div className="flex items-center gap-2 text-amber-800 dark:text-amber-200">
          <Activity className="w-5 h-5" />
          <span className="font-medium">Live monitoring</span>
        </div>
        <p className="mt-2 text-sm text-amber-700 dark:text-amber-300">
          System metrics, processes, and network stats are polled every 3 seconds.
        </p>
      </div>
    </div>
  )
}

function StatCard({
  icon,
  title,
  value,
  subtitle,
  percent,
}: {
  icon: React.ReactNode
  title: string
  value: string
  subtitle: string
  percent: number
}) {
  const barColor = percent > 90 ? 'bg-red-500' : percent > 70 ? 'bg-amber-500' : 'bg-blue-500'
  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow border border-gray-200 dark:border-gray-700 p-6">
      <div className="flex items-center gap-4 mb-4">
        <div className="p-3 rounded-lg bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400">
          {icon}
        </div>
        <div>
          <p className="text-sm text-gray-500 dark:text-gray-400">{title}</p>
          <p className="text-xl font-bold text-gray-800 dark:text-white">{value}</p>
          <p className="text-xs text-gray-500">{subtitle}</p>
        </div>
      </div>
      <div className="h-2 bg-gray-200 dark:bg-gray-700 rounded-full overflow-hidden">
        <div
          className={`h-full ${barColor} transition-all duration-500`}
          style={{ width: `${Math.min(percent, 100)}%` }}
        />
      </div>
    </div>
  )
}
