import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { monitoringApi } from '@/api/monitoring'
import { systemAPI } from '@/api/system'
import { zfsApi } from '@/api/storage'
import { formatBytes } from '@/lib/format'
import {
  RefreshCw,
  TrendingDown,
  CheckCircle2,
  Cpu,
  MemoryStick,
  HardDrive,
  Clock,
  Search,
  AlertCircle,
  Info,
  AlertTriangle
} from 'lucide-react'
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  Area,
  AreaChart,
} from 'recharts'

const MOCK_ACTIVE_JOBS = [
  {
    id: '1',
    name: 'Daily Backup: VM-Cluster-01',
    type: 'Replication',
    progress: 45,
    speed: '145 MB/s',
    status: 'running',
    eta: '1h 12m',
  },
  {
    id: '2',
    name: 'ZFS Scrub: Pool-01',
    type: 'Maintenance',
    progress: 78,
    speed: '1.2 GB/s',
    status: 'running',
  },
]

export default function Monitoring() {
  const [activeTab, setActiveTab] = useState<'jobs' | 'logs' | 'alerts'>('jobs')
  const [searchQuery, setSearchQuery] = useState('')
  const refreshInterval = 5

  // Fetch metrics
  const { data: metrics, isLoading: metricsLoading } = useQuery({
    queryKey: ['monitoring-metrics'],
    queryFn: monitoringApi.getMetrics,
    refetchInterval: refreshInterval * 1000,
  })

  // Fetch system logs
  const { data: systemLogs = [], isLoading: logsLoading } = useQuery({
    queryKey: ['monitoring-logs'],
    queryFn: () => systemAPI.getSystemLogs(50),
    refetchInterval: 10 * 1000,
  })

  // Fetch network throughput
  const { data: networkData = [] } = useQuery({
    queryKey: ['monitoring-network'],
    queryFn: () => systemAPI.getNetworkThroughput('15m'),
    refetchInterval: refreshInterval * 1000,
  })

  // Fetch ZFS pools for health status
  const { data: pools = [] } = useQuery({
    queryKey: ['monitoring-pools'],
    queryFn: zfsApi.listPools,
    refetchInterval: 30 * 1000,
  })

  // Fetch alerts
  const { data: alertsData } = useQuery({
    queryKey: ['monitoring-alerts'],
    queryFn: () => monitoringApi.listAlerts({ limit: 20 }),
    refetchInterval: 10 * 1000,
  })

  // Format uptime
  const formatUptime = (seconds: number) => {
    const days = Math.floor(seconds / 86400)
    const hours = Math.floor((seconds % 86400) / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    return `${days}d ${hours}h ${minutes}m`
  }

  // Get ZFS pool health
  const zfsHealth = pools.length > 0 ? pools[0] : null
  const zfsStatus = zfsHealth?.health_status === 'online' ? 'Online' : 'Degraded'
  const zfsHealthy = zfsHealth?.health_status === 'online'

  // Filter logs by search query
  const filteredLogs = systemLogs.filter(log =>
    log.message.toLowerCase().includes(searchQuery.toLowerCase()) ||
    log.source.toLowerCase().includes(searchQuery.toLowerCase())
  )

  // Get log level color
  const getLogLevelColor = (level: string) => {
    const upperLevel = level.toUpperCase()
    if (upperLevel === 'INFO' || upperLevel === 'DEBUG') return 'text-emerald-500'
    if (upperLevel === 'WARN' || upperLevel === 'WARNING') return 'text-yellow-500'
    if (upperLevel === 'ERROR' || upperLevel === 'CRITICAL' || upperLevel === 'FATAL') return 'text-red-500'
    return 'text-text-secondary'
  }

  // Calculate network peak
  const networkPeak = networkData.length > 0
    ? Math.max(...networkData.map(d => Math.max(d.inbound, d.outbound)))
    : 0

  // Calculate current network throughput (convert Mbps to Gbps)
  const currentThroughput = networkData.length > 0
    ? ((networkData[networkData.length - 1].inbound + networkData[networkData.length - 1].outbound) / 1000).toFixed(1)
    : '0.0'

  return (
    <div className="flex-1 overflow-hidden flex flex-col bg-background-dark">
      {/* Header */}
      <header className="flex-none px-6 py-5 border-b border-border-dark bg-background-dark/95 backdrop-blur z-10">
        <div className="flex flex-wrap justify-between items-end gap-3 max-w-[1600px] mx-auto">
          <div className="flex flex-col gap-1">
            <h2 className="text-white text-3xl font-black tracking-tight">System Monitor</h2>
            <p className="text-text-secondary text-sm">Real-time telemetry, ZFS health, and system event logs</p>
          </div>
          <div className="flex items-center gap-3">
            <div className="flex items-center gap-2 px-3 py-2 bg-card-dark rounded-lg border border-border-dark">
              <span className="relative flex h-2 w-2">
                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                <span className="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>
              </span>
              <span className="text-xs font-medium text-emerald-400">System Healthy</span>
            </div>
            <button className="flex items-center gap-2 h-10 px-4 bg-card-dark hover:bg-[#233648] border border-border-dark text-white text-sm font-bold rounded-lg transition-colors">
              <RefreshCw size={18} />
              <span>Refresh: {refreshInterval}s</span>
            </button>
          </div>
        </div>
      </header>

      {/* Scrollable Content */}
      <div className="flex-1 overflow-y-auto custom-scrollbar p-6">
        <div className="flex flex-col gap-6 max-w-[1600px] mx-auto pb-10">
          {/* Top Stats Row */}
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {/* CPU */}
            <div className="flex flex-col gap-2 rounded-xl p-5 border border-border-dark bg-card-dark">
              <div className="flex justify-between items-start">
                <p className="text-text-secondary text-sm font-medium">CPU Load</p>
                <Cpu className="text-text-secondary" size={20} />
              </div>
              <div className="flex items-end gap-3 mt-1">
                <p className="text-white text-3xl font-bold">
                  {metricsLoading ? '...' : `${metrics?.system?.cpu_usage_percent?.toFixed(0) || 0}%`}
                </p>
                <span className="text-emerald-500 text-sm font-medium mb-1 flex items-center">
                  <TrendingDown size={16} className="mr-1" />
                  2%
                </span>
              </div>
              <div className="h-1.5 w-full bg-[#233648] rounded-full mt-3 overflow-hidden">
                <div
                  className="h-full bg-primary rounded-full transition-all"
                  style={{ width: `${metrics?.system?.cpu_usage_percent || 0}%` }}
                ></div>
              </div>
            </div>

            {/* RAM */}
            <div className="flex flex-col gap-2 rounded-xl p-5 border border-border-dark bg-card-dark">
              <div className="flex justify-between items-start">
                <p className="text-text-secondary text-sm font-medium">RAM Usage</p>
                <MemoryStick className="text-text-secondary" size={20} />
              </div>
              <div className="flex items-end gap-3 mt-1">
                <p className="text-white text-3xl font-bold">
                  {metricsLoading ? '...' : formatBytes(metrics?.system?.memory_used_bytes || 0)}
                </p>
                <span className="text-text-secondary text-xs mb-2">
                  / {formatBytes(metrics?.system?.memory_total_bytes || 0)}
                </span>
              </div>
              <div className="h-1.5 w-full bg-[#233648] rounded-full mt-3 overflow-hidden">
                <div
                  className="h-full bg-emerald-500 rounded-full transition-all"
                  style={{ width: `${metrics?.system?.memory_usage_percent || 0}%` }}
                ></div>
              </div>
            </div>

            {/* ZFS Health */}
            <div className="flex flex-col gap-2 rounded-xl p-5 border border-border-dark bg-card-dark">
              <div className="flex justify-between items-start">
                <p className="text-text-secondary text-sm font-medium">ZFS Pool Status</p>
                <CheckCircle2 className={zfsHealthy ? 'text-emerald-500' : 'text-yellow-500'} size={20} />
              </div>
              <div className="flex items-end gap-3 mt-1">
                <p className="text-white text-3xl font-bold">{zfsStatus}</p>
                <span className="text-text-secondary text-sm font-medium mb-1">No Errors</span>
              </div>
              <div className="flex gap-1 mt-3">
                {[1, 2, 3, 4].map((i) => (
                  <div
                    key={i}
                    className={`h-1.5 flex-1 rounded-full ${
                      i === 1 ? 'rounded-l-full' : i === 4 ? 'rounded-r-full' : ''
                    } ${zfsHealthy ? 'bg-emerald-500' : 'bg-yellow-500'}`}
                  ></div>
                ))}
              </div>
            </div>

            {/* Uptime */}
            <div className="flex flex-col gap-2 rounded-xl p-5 border border-border-dark bg-card-dark">
              <div className="flex justify-between items-start">
                <p className="text-text-secondary text-sm font-medium">System Uptime</p>
                <Clock className="text-text-secondary" size={20} />
              </div>
              <div className="mt-1">
                <p className="text-white text-3xl font-bold">
                  {metricsLoading ? '...' : formatUptime(metrics?.system?.uptime_seconds || 0)}
                </p>
              </div>
              <p className="text-text-secondary text-xs mt-3">Last reboot: Manual Patching</p>
            </div>
          </div>

          {/* Middle Section: Charts & Disks */}
          <div className="grid grid-cols-1 xl:grid-cols-3 gap-6">
            {/* Charts Column (2/3) */}
            <div className="xl:col-span-2 flex flex-col gap-6">
              {/* Network Chart */}
              <div className="bg-card-dark border border-border-dark rounded-xl p-6 shadow-sm">
                <div className="flex justify-between items-center mb-6">
                  <div>
                    <h3 className="text-white text-lg font-bold">Network Throughput</h3>
                    <p className="text-text-secondary text-sm">Inbound vs Outbound (eth0)</p>
                  </div>
                  <div className="text-right">
                    <p className="text-white text-2xl font-bold leading-tight">{currentThroughput} Gbps</p>
                    <p className="text-emerald-500 text-sm">Peak: {(networkPeak / 1000).toFixed(1)} Gbps</p>
                  </div>
                </div>
                <div className="h-[200px] w-full">
                  {networkData.length > 0 ? (
                    <ResponsiveContainer width="100%" height="100%">
                      <AreaChart data={networkData.map(d => ({
                        time: new Date(d.time).toLocaleTimeString(),
                        inbound: d.inbound,
                        outbound: d.outbound,
                      }))}>
                        <defs>
                          <linearGradient id="gradientPrimary" x1="0" x2="0" y1="0" y2="1">
                            <stop offset="0%" stopColor="#137fec" stopOpacity={0.2} />
                            <stop offset="100%" stopColor="#137fec" stopOpacity={0} />
                          </linearGradient>
                        </defs>
                        <CartesianGrid strokeDasharray="3 3" stroke="#324d67" />
                        <XAxis dataKey="time" stroke="#92adc9" style={{ fontSize: '12px' }} />
                        <YAxis stroke="#92adc9" style={{ fontSize: '12px' }} />
                        <Tooltip
                          contentStyle={{
                            backgroundColor: '#1a2632',
                            border: '1px solid #324d67',
                            borderRadius: '0.5rem',
                          }}
                        />
                        <Legend />
                        <Area
                          type="monotone"
                          dataKey="outbound"
                          stroke="#92adc9"
                          strokeDasharray="5 5"
                          strokeWidth={2}
                          fill="none"
                        />
                        <Area
                          type="monotone"
                          dataKey="inbound"
                          stroke="#137fec"
                          strokeWidth={3}
                          fill="url(#gradientPrimary)"
                        />
                      </AreaChart>
                    </ResponsiveContainer>
                  ) : (
                    <div className="h-full flex items-center justify-center text-text-secondary">
                      Loading network data...
                    </div>
                  )}
                </div>
              </div>

              {/* ZFS ARC Chart */}
              <div className="bg-card-dark border border-border-dark rounded-xl p-6 shadow-sm">
                <div className="flex justify-between items-center mb-6">
                  <div>
                    <h3 className="text-white text-lg font-bold">ZFS ARC Hit Ratio</h3>
                    <p className="text-text-secondary text-sm">Cache efficiency</p>
                  </div>
                  <div className="text-right">
                    <p className="text-white text-2xl font-bold leading-tight">94%</p>
                    <p className="text-text-secondary text-sm">Target: &gt;90%</p>
                  </div>
                </div>
                <div className="h-[150px] w-full relative">
                  <ResponsiveContainer width="100%" height="100%">
                    <LineChart data={[
                      { time: '10:00', ratio: 95 },
                      { time: '10:15', ratio: 94 },
                      { time: '10:30', ratio: 96 },
                      { time: '10:45', ratio: 93 },
                      { time: '11:00', ratio: 94 },
                    ]}>
                      <CartesianGrid strokeDasharray="3 3" stroke="#324d67" />
                      <XAxis dataKey="time" stroke="#92adc9" style={{ fontSize: '12px' }} />
                      <YAxis stroke="#92adc9" domain={[90, 100]} style={{ fontSize: '12px' }} />
                      <Tooltip
                        contentStyle={{
                          backgroundColor: '#1a2632',
                          border: '1px solid #324d67',
                          borderRadius: '0.5rem',
                        }}
                      />
                      <Line
                        type="monotone"
                        dataKey="ratio"
                        stroke="#10b981"
                        strokeWidth={2}
                        dot={false}
                      />
                    </LineChart>
                  </ResponsiveContainer>
                  <div className="w-full h-[1px] bg-border-dark absolute top-[20%]"></div>
                  <div className="absolute top-[20%] right-0 text-xs text-text-secondary -mt-5">95%</div>
                </div>
              </div>
            </div>

            {/* Disk Health Column (1/3) */}
            <div className="flex flex-col gap-6">
              <div className="bg-card-dark border border-border-dark rounded-xl p-6 h-full shadow-sm flex flex-col">
                <div className="flex justify-between items-center mb-4">
                  <h3 className="text-white text-lg font-bold">Disk Health</h3>
                  <span className="bg-[#233648] text-white text-xs px-2 py-1 rounded border border-border-dark">
                    Pool 1
                  </span>
                </div>
                <div className="grid grid-cols-4 gap-3 flex-1 content-start">
                  {/* Mock disk health - would be replaced with real data */}
                  {[0, 1, 2, 3, 4, 5, 6, 7].map((i) => (
                    <div
                      key={i}
                      className={`aspect-square border rounded flex flex-col items-center justify-center ${
                        i === 5
                          ? 'bg-[#332a18] border-yellow-700/50'
                          : 'bg-[#1a2e22] border-emerald-800'
                      }`}
                    >
                      {i === 5 ? (
                        <>
                          <span className="absolute top-1 right-1 h-2 w-2 rounded-full bg-yellow-500 animate-pulse"></span>
                          <AlertTriangle className="text-yellow-500" size={20} />
                        </>
                      ) : (
                        <HardDrive className="text-emerald-500" size={20} />
                      )}
                      <span className={`text-[10px] font-mono mt-1 ${
                        i === 5 ? 'text-yellow-500' : 'text-emerald-500'
                      }`}>
                        da{i}
                      </span>
                    </div>
                  ))}
                  {/* Empty slots */}
                  {[8, 9, 10, 11].map((i) => (
                    <div
                      key={i}
                      className="aspect-square bg-[#161f29] border border-border-dark border-dashed rounded flex flex-col items-center justify-center opacity-50"
                    >
                      <span className="text-[10px] text-text-secondary font-mono">Empty</span>
                    </div>
                  ))}
                </div>
                <div className="mt-4 pt-4 border-t border-border-dark">
                  <div className="flex justify-between text-sm text-text-secondary">
                    <span>Total Capacity</span>
                    <span className="text-white font-bold">
                      {formatBytes(metrics?.storage?.total_capacity_bytes || 0)}
                    </span>
                  </div>
                  <div className="w-full bg-[#233648] h-2 rounded-full mt-2 overflow-hidden">
                    <div
                      className="bg-primary h-full transition-all"
                      style={{
                        width: `${
                          metrics?.storage?.total_capacity_bytes
                            ? (metrics.storage.used_capacity_bytes / metrics.storage.total_capacity_bytes) * 100
                            : 0
                        }%`,
                      }}
                    ></div>
                  </div>
                  <div className="flex justify-between text-xs text-text-secondary mt-1">
                    <span>Used: {formatBytes(metrics?.storage?.used_capacity_bytes || 0)}</span>
                    <span>Free: {formatBytes((metrics?.storage?.total_capacity_bytes || 0) - (metrics?.storage?.used_capacity_bytes || 0))}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* Bottom Section: Tabs & Logs */}
          <div className="bg-card-dark border border-border-dark rounded-xl shadow-sm overflow-hidden flex flex-col h-[400px]">
            {/* Tabs Header */}
            <div className="flex border-b border-border-dark bg-[#161f29]">
              <button
                onClick={() => setActiveTab('jobs')}
                className={`px-6 py-4 text-sm font-bold flex items-center transition-colors ${
                  activeTab === 'jobs'
                    ? 'text-primary border-b-2 border-primary bg-card-dark'
                    : 'text-text-secondary hover:text-white'
                }`}
              >
                Active Jobs{' '}
                <span className="ml-2 bg-primary/20 text-primary px-1.5 py-0.5 rounded text-xs">
                  {MOCK_ACTIVE_JOBS.length}
                </span>
              </button>
              <button
                onClick={() => setActiveTab('logs')}
                className={`px-6 py-4 text-sm transition-colors ${
                  activeTab === 'logs'
                    ? 'text-primary border-b-2 border-primary bg-card-dark font-bold'
                    : 'text-text-secondary hover:text-white font-medium'
                }`}
              >
                System Logs
              </button>
              <button
                onClick={() => setActiveTab('alerts')}
                className={`px-6 py-4 text-sm transition-colors ${
                  activeTab === 'alerts'
                    ? 'text-primary border-b-2 border-primary bg-card-dark font-bold'
                    : 'text-text-secondary hover:text-white font-medium'
                }`}
              >
                Alerts History
              </button>
              <div className="flex-1 flex justify-end items-center px-4">
                <div className="relative">
                  <Search className="absolute left-2 top-1.5 text-text-secondary" size={18} />
                  <input
                    className="bg-[#111a22] border border-border-dark rounded-md py-1 pl-8 pr-3 text-sm text-white focus:outline-none focus:border-primary w-48 transition-all"
                    placeholder="Search logs..."
                    type="text"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                  />
                </div>
              </div>
            </div>

            {/* Tab Content */}
            <div className="flex-1 overflow-hidden flex flex-col">
              {activeTab === 'jobs' && (
                <div className="p-0 overflow-y-auto custom-scrollbar">
                  <table className="w-full text-left border-collapse">
                    <thead className="bg-[#1a2632] text-xs uppercase text-text-secondary font-medium sticky top-0 z-10">
                      <tr>
                        <th className="px-6 py-3 border-b border-border-dark">Job Name</th>
                        <th className="px-6 py-3 border-b border-border-dark">Type</th>
                        <th className="px-6 py-3 border-b border-border-dark w-1/3">Progress</th>
                        <th className="px-6 py-3 border-b border-border-dark">Speed</th>
                        <th className="px-6 py-3 border-b border-border-dark">Status</th>
                      </tr>
                    </thead>
                    <tbody className="text-sm divide-y divide-border-dark">
                      {MOCK_ACTIVE_JOBS.map((job) => (
                        <tr key={job.id} className="group hover:bg-[#233648] transition-colors">
                          <td className="px-6 py-4 font-medium text-white">{job.name}</td>
                          <td className="px-6 py-4 text-text-secondary">{job.type}</td>
                          <td className="px-6 py-4">
                            <div className="flex items-center gap-3">
                              <div className="w-full bg-[#111a22] rounded-full h-2 overflow-hidden">
                                <div
                                  className="bg-primary h-full rounded-full relative overflow-hidden"
                                  style={{ width: `${job.progress}%` }}
                                >
                                  <div className="absolute inset-0 bg-white/20 animate-pulse"></div>
                                </div>
                              </div>
                              <span className="text-xs font-mono text-white">{job.progress}%</span>
                            </div>
                            {job.eta && (
                              <p className="text-[10px] text-text-secondary mt-1">ETA: {job.eta}</p>
                            )}
                          </td>
                          <td className="px-6 py-4 text-text-secondary font-mono">{job.speed}</td>
                          <td className="px-6 py-4">
                            <span className="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-primary/20 text-primary">
                              Running
                            </span>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              )}

              {activeTab === 'logs' && (
                <>
                  {/* Logs Section Header */}
                  <div className="px-6 py-2 bg-[#161f29] border-y border-border-dark flex items-center justify-between">
                    <h4 className="text-xs uppercase text-text-secondary font-bold tracking-wider">
                      Recent System Events
                    </h4>
                    <button className="text-xs text-primary hover:text-white transition-colors">
                      View All Logs
                    </button>
                  </div>
                  {/* Logs Table */}
                  <div className="flex-1 overflow-y-auto custom-scrollbar bg-[#111a22]">
                    <table className="w-full text-left border-collapse">
                      <tbody className="text-sm font-mono divide-y divide-border-dark/50">
                        {logsLoading ? (
                          <tr>
                            <td colSpan={4} className="px-6 py-4 text-center text-text-secondary">
                              Loading logs...
                            </td>
                          </tr>
                        ) : filteredLogs.length === 0 ? (
                          <tr>
                            <td colSpan={4} className="px-6 py-4 text-center text-text-secondary">
                              No logs found
                            </td>
                          </tr>
                        ) : (
                          filteredLogs.map((log, idx) => (
                            <tr key={idx} className="group hover:bg-[#233648] transition-colors">
                              <td className="px-6 py-2 text-text-secondary w-32 whitespace-nowrap">
                                {new Date(log.time).toLocaleTimeString()}
                              </td>
                              <td className="px-6 py-2 w-24">
                                <span className={getLogLevelColor(log.level)}>{log.level}</span>
                              </td>
                              <td className="px-6 py-2 w-32 text-white">{log.source}</td>
                              <td className="px-6 py-2 text-text-secondary truncate max-w-lg">{log.message}</td>
                            </tr>
                          ))
                        )}
                      </tbody>
                    </table>
                  </div>
                </>
              )}

              {activeTab === 'alerts' && (
                <div className="flex-1 overflow-y-auto custom-scrollbar bg-[#111a22] p-6">
                  {alertsData?.alerts && alertsData.alerts.length > 0 ? (
                    <div className="space-y-3">
                      {alertsData.alerts.map((alert) => (
                        <div
                          key={alert.id}
                          className="bg-[#1a2632] border border-border-dark rounded-lg p-4 hover:bg-[#233648] transition-colors"
                        >
                          <div className="flex items-start justify-between">
                            <div className="flex items-start gap-3">
                              {alert.severity === 'critical' ? (
                                <AlertCircle className="text-red-500 mt-1" size={20} />
                              ) : alert.severity === 'warning' ? (
                                <AlertTriangle className="text-yellow-500 mt-1" size={20} />
                              ) : (
                                <Info className="text-blue-500 mt-1" size={20} />
                              )}
                              <div>
                                <h4 className="text-white font-medium">{alert.title}</h4>
                                <p className="text-text-secondary text-sm mt-1">{alert.message}</p>
                                <p className="text-text-secondary text-xs mt-2">
                                  {new Date(alert.created_at).toLocaleString()}
                                </p>
                              </div>
                            </div>
                            <span
                              className={`px-2 py-1 rounded text-xs font-medium ${
                                alert.severity === 'critical'
                                  ? 'bg-red-500/20 text-red-400'
                                  : alert.severity === 'warning'
                                  ? 'bg-yellow-500/20 text-yellow-400'
                                  : 'bg-blue-500/20 text-blue-400'
                              }`}
                            >
                              {alert.severity.toUpperCase()}
                            </span>
                          </div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div className="text-center text-text-secondary py-8">No alerts</div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

