import React, { useState, useEffect } from 'react';
import { Activity, Server, Database, HardDrive, Clock, AlertTriangle, CheckCircle, XCircle, RefreshCw, Cpu, MemoryStick, Zap, Shield, Calendar, TrendingUp, Settings, Bell, Search, ChevronDown, ChevronRight, Play, Pause, BarChart3, PieChart, ArrowUpRight, ArrowDownRight, Timer, Layers, GitBranch, Mail, FileText, Terminal } from 'lucide-react';

// Simulated data based on the DBAOps discovery report
const mockData = {
  summary: {
    totalServers: 110,
    reachable: 108,
    unreachable: 2,
    prodServers: 75,
    nonProdServers: 35,
    totalDatabases: 1230,
    totalJobs: 152,
    enabledJobs: 145,
    failedJobs24h: 6,
    dbSizeMB: 12729.81,
    dbUsedMB: 11752.00
  },
  reachability: {
    online: 108,
    offline: 2,
    percentage: 98.2,
    unreachableServers: ['AZLUASRSQL01', 'AZPBIRSSQL01']
  },
  healthMetrics: {
    backup: { status: 'OK', compliance: 96.5, lastCheck: '2025-12-22 08:15:00' },
    diskSpace: { status: 'OK', avgUsage: 62.3, criticalCount: 0 },
    replication: { status: 'OK', latency: 45, pendingCmds: 0 },
    jobs: { status: 'WARNING', failedCount: 6, successRate: 97.2 },
    cms: { status: 'OK', syncPercentage: 99.09 }
  },
  jobCategories: [
    { name: 'Database Maintenance', count: 67, enabled: 62 },
    { name: 'Uncategorized (Local)', count: 62, enabled: 61 },
    { name: 'DBAOps – HealthChecks', count: 5, enabled: 5 },
    { name: 'DBAOps – Audit', count: 4, enabled: 4 },
    { name: 'DBAOps Monitoring', count: 3, enabled: 3 }
  ],
  scheduleFrequency: [
    { type: 'Daily (Once)', count: 54 },
    { type: 'Every 15 min', count: 23 },
    { type: 'Weekly', count: 16 },
    { type: 'Every 1 hour', count: 15 },
    { type: 'Every 5 min', count: 15 }
  ],
  failedJobs: [
    { name: 'DBAOps – Backup SLA Monitor', error: 'Invalid object name \'fact.BackupHealth\'', time: '08:15:00', count: 48 },
    { name: 'DBAOps – Schedule AutoFix', error: 'Job \'DBAOps – Backup Compliance Collector\' does not exist', time: '08:15:02', count: 12 },
    { name: 'DBAOps - Throttle External Processes', error: 'PowerShell script error', time: '06:05:06', count: 12 },
    { name: 'DBAOps – FACT AutoHeal', error: 'Invalid object name \'fact.Performance\'', time: '07:05:00', count: 1 },
    { name: 'Sql Backup check Notification', error: 'String or binary data truncated', time: '08:00:14', count: 2 },
    { name: 'DBAOps - Daily SQL Patch Compliance', error: 'Syntax error at line 26', time: '06:00:01', count: 1 }
  ],
  schemas: [
    { name: 'fact', tables: 25, procedures: 9, purpose: 'Historical/metric data storage' },
    { name: 'ctl', tables: 20, procedures: 43, purpose: 'Process control and staging' },
    { name: 'config', tables: 23, procedures: 4, purpose: 'System settings' },
    { name: 'DBAOps', tables: 22, procedures: 15, purpose: 'Core framework objects' },
    { name: 'Patching', tables: 18, procedures: 31, purpose: 'Patch management' },
    { name: 'audit', tables: 12, procedures: 9, purpose: 'Change tracking' },
    { name: 'metrics', tables: 2, procedures: 2, purpose: 'Performance data' },
    { name: 'alert', tables: 0, procedures: 13, purpose: 'Notification logic' }
  ],
  topTables: [
    { schema: 'DBAOps', name: 'PerformanceTelemetry', rows: 80607800, sizeMB: 10902.77 },
    { schema: 'ctl', name: 'VeeamBackups', rows: 508222, sizeMB: 55.53 },
    { schema: 'fact', name: 'BackupCompliance', rows: 501221, sizeMB: 92.34 },
    { schema: 'fact', name: 'ServerHealth', rows: 190248, sizeMB: 11.08 },
    { schema: 'fact', name: 'MemoryCompliance', rows: 189921, sizeMB: 8.95 }
  ],
  servers: {
    prod: [
      { name: 'AZDBAOPSSQL01', status: 'online', cpu: 23, memory: 68, databases: 4 },
      { name: 'AZSPILLMANSQL19', status: 'online', cpu: 45, memory: 72, databases: 12 },
      { name: 'AZTRACSSQL16', status: 'online', cpu: 31, memory: 55, databases: 8 },
      { name: 'AZRPTSQL19', status: 'online', cpu: 18, memory: 42, databases: 6 },
      { name: 'AZLUASRSQL01', status: 'offline', cpu: 0, memory: 0, databases: 3 },
      { name: 'AZPBIRSSQL01', status: 'offline', cpu: 0, memory: 0, databases: 5 }
    ],
    nonProd: [
      { name: 'AZSCDSQL01T', status: 'online', cpu: 12, memory: 35, databases: 2 },
      { name: 'AZTRACSSQL16T', status: 'online', cpu: 8, memory: 28, databases: 4 },
      { name: 'AZWEBFSQL22D', status: 'online', cpu: 15, memory: 41, databases: 3 }
    ]
  },
  recentAlerts: [
    { type: 'critical', message: '2 servers unreachable', time: '07:50:31', source: 'Reachability Check' },
    { type: 'warning', message: '6 jobs failed in last 24h', time: '08:00:00', source: 'Job Monitor' },
    { type: 'info', message: 'Daily backup compliance: 96.5%', time: '07:05:00', source: 'Backup Monitor' }
  ]
};

const StatusBadge = ({ status, size = 'md' }) => {
  const colors = {
    OK: 'bg-emerald-500/20 text-emerald-400 border-emerald-500/30',
    WARNING: 'bg-amber-500/20 text-amber-400 border-amber-500/30',
    CRITICAL: 'bg-red-500/20 text-red-400 border-red-500/30',
    online: 'bg-emerald-500/20 text-emerald-400 border-emerald-500/30',
    offline: 'bg-red-500/20 text-red-400 border-red-500/30'
  };
  const sizes = {
    sm: 'px-2 py-0.5 text-xs',
    md: 'px-3 py-1 text-sm'
  };
  return (
    <span className={`${colors[status] || colors.OK} ${sizes[size]} rounded-full border font-medium`}>
      {status}
    </span>
  );
};

const MetricCard = ({ icon: Icon, title, value, subtitle, trend, status, onClick }) => (
  <div 
    onClick={onClick}
    className={`bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-xl p-5 hover:border-cyan-500/30 transition-all duration-300 ${onClick ? 'cursor-pointer hover:scale-[1.02]' : ''}`}
  >
    <div className="flex items-start justify-between mb-3">
      <div className={`p-2.5 rounded-lg ${status === 'CRITICAL' ? 'bg-red-500/20' : status === 'WARNING' ? 'bg-amber-500/20' : 'bg-cyan-500/20'}`}>
        <Icon className={`w-5 h-5 ${status === 'CRITICAL' ? 'text-red-400' : status === 'WARNING' ? 'text-amber-400' : 'text-cyan-400'}`} />
      </div>
      {trend && (
        <div className={`flex items-center gap-1 text-sm ${trend > 0 ? 'text-emerald-400' : 'text-red-400'}`}>
          {trend > 0 ? <ArrowUpRight className="w-4 h-4" /> : <ArrowDownRight className="w-4 h-4" />}
          {Math.abs(trend)}%
        </div>
      )}
    </div>
    <div className="text-2xl font-bold text-white mb-1">{value}</div>
    <div className="text-slate-400 text-sm">{title}</div>
    {subtitle && <div className="text-slate-500 text-xs mt-1">{subtitle}</div>}
  </div>
);

const ProgressRing = ({ progress, size = 80, strokeWidth = 8, color = 'cyan' }) => {
  const radius = (size - strokeWidth) / 2;
  const circumference = radius * 2 * Math.PI;
  const offset = circumference - (progress / 100) * circumference;
  const colors = {
    cyan: '#06b6d4',
    emerald: '#10b981',
    amber: '#f59e0b',
    red: '#ef4444'
  };
  return (
    <svg width={size} height={size} className="transform -rotate-90">
      <circle cx={size/2} cy={size/2} r={radius} stroke="rgba(255,255,255,0.1)" strokeWidth={strokeWidth} fill="none" />
      <circle cx={size/2} cy={size/2} r={radius} stroke={colors[color]} strokeWidth={strokeWidth} fill="none" strokeLinecap="round" strokeDasharray={circumference} strokeDashoffset={offset} className="transition-all duration-1000" />
    </svg>
  );
};

const MiniChart = ({ data, color = '#06b6d4' }) => {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const points = data.map((v, i) => `${(i / (data.length - 1)) * 100},${100 - ((v - min) / range) * 80}`).join(' ');
  return (
    <svg viewBox="0 0 100 100" className="w-full h-12">
      <polyline fill="none" stroke={color} strokeWidth="2" points={points} />
      <polyline fill={`${color}20`} stroke="none" points={`0,100 ${points} 100,100`} />
    </svg>
  );
};

const Sidebar = ({ activeTab, setActiveTab }) => {
  const tabs = [
    { id: 'dashboard', icon: Activity, label: 'Dashboard' },
    { id: 'servers', icon: Server, label: 'Servers' },
    { id: 'jobs', icon: Clock, label: 'SQL Agent Jobs' },
    { id: 'databases', icon: Database, label: 'Databases' },
    { id: 'alerts', icon: Bell, label: 'Alerts' },
    { id: 'reports', icon: FileText, label: 'Reports' },
    { id: 'settings', icon: Settings, label: 'Settings' }
  ];
  
  return (
    <div className="w-64 bg-slate-900/80 backdrop-blur-xl border-r border-slate-700/50 flex flex-col">
      <div className="p-6 border-b border-slate-700/50">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-xl bg-gradient-to-br from-cyan-500 to-blue-600 flex items-center justify-center">
            <Database className="w-5 h-5 text-white" />
          </div>
          <div>
            <h1 className="text-lg font-bold text-white">DBAOps</h1>
            <p className="text-xs text-slate-400">Monitoring Framework</p>
          </div>
        </div>
      </div>
      
      <nav className="flex-1 p-4 space-y-1">
        {tabs.map(tab => (
          <button
            key={tab.id}
            onClick={() => setActiveTab(tab.id)}
            className={`w-full flex items-center gap-3 px-4 py-3 rounded-lg transition-all duration-200 ${
              activeTab === tab.id 
                ? 'bg-cyan-500/20 text-cyan-400 border border-cyan-500/30' 
                : 'text-slate-400 hover:bg-slate-800/50 hover:text-white'
            }`}
          >
            <tab.icon className="w-5 h-5" />
            <span className="font-medium">{tab.label}</span>
          </button>
        ))}
      </nav>
      
      <div className="p-4 border-t border-slate-700/50">
        <div className="bg-slate-800/50 rounded-lg p-4">
          <div className="flex items-center gap-2 mb-2">
            <div className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
            <span className="text-sm text-slate-300">System Status</span>
          </div>
          <p className="text-xs text-slate-500">All services operational</p>
          <p className="text-xs text-slate-600 mt-1">Last sync: Just now</p>
        </div>
      </div>
    </div>
  );
};

const Header = ({ onRefresh, lastUpdate }) => (
  <header className="h-16 bg-slate-900/50 backdrop-blur-sm border-b border-slate-700/50 flex items-center justify-between px-6">
    <div className="flex items-center gap-4">
      <div className="relative">
        <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-500" />
        <input 
          type="text" 
          placeholder="Search servers, jobs, databases..." 
          className="w-80 bg-slate-800/50 border border-slate-700/50 rounded-lg pl-10 pr-4 py-2 text-sm text-slate-300 placeholder-slate-500 focus:outline-none focus:border-cyan-500/50"
        />
      </div>
    </div>
    
    <div className="flex items-center gap-4">
      <span className="text-sm text-slate-500">Last updated: {lastUpdate}</span>
      <button onClick={onRefresh} className="p-2 rounded-lg bg-slate-800/50 hover:bg-slate-700/50 text-slate-400 hover:text-cyan-400 transition-colors">
        <RefreshCw className="w-5 h-5" />
      </button>
      <button className="relative p-2 rounded-lg bg-slate-800/50 hover:bg-slate-700/50 text-slate-400 hover:text-cyan-400 transition-colors">
        <Bell className="w-5 h-5" />
        <span className="absolute -top-1 -right-1 w-4 h-4 bg-red-500 rounded-full text-xs text-white flex items-center justify-center">3</span>
      </button>
      <div className="flex items-center gap-3 pl-4 border-l border-slate-700/50">
        <div className="w-8 h-8 rounded-full bg-gradient-to-br from-cyan-500 to-blue-600 flex items-center justify-center text-white text-sm font-medium">
          JG
        </div>
        <div className="text-sm">
          <p className="text-slate-300 font-medium">John Gakumba</p>
          <p className="text-slate-500 text-xs">Sr. SQL DBA</p>
        </div>
      </div>
    </div>
  </header>
);

const DashboardTab = ({ data }) => {
  const cpuHistory = [23, 28, 35, 42, 38, 31, 27, 33, 29, 25, 28, 23];
  const memoryHistory = [62, 65, 68, 71, 69, 66, 64, 67, 70, 68, 65, 68];
  
  return (
    <div className="space-y-6">
      {/* Status Overview */}
      <div className="grid grid-cols-5 gap-4">
        <MetricCard 
          icon={Server} 
          title="Total Servers" 
          value={data.summary.totalServers}
          subtitle={`${data.summary.prodServers} prod / ${data.summary.nonProdServers} non-prod`}
        />
        <MetricCard 
          icon={CheckCircle} 
          title="Reachable" 
          value={`${data.reachability.online}/${data.summary.totalServers}`}
          subtitle={`${data.reachability.percentage}% online`}
          status={data.reachability.offline > 0 ? 'WARNING' : 'OK'}
        />
        <MetricCard 
          icon={Database} 
          title="Databases" 
          value={data.summary.totalDatabases.toLocaleString()}
          subtitle="Across all instances"
        />
        <MetricCard 
          icon={Clock} 
          title="SQL Agent Jobs" 
          value={data.summary.enabledJobs}
          subtitle={`${data.summary.failedJobs24h} failed (24h)`}
          status={data.summary.failedJobs24h > 5 ? 'WARNING' : 'OK'}
        />
        <MetricCard 
          icon={HardDrive} 
          title="Repository Size" 
          value={`${(data.summary.dbSizeMB / 1024).toFixed(1)} GB`}
          subtitle={`${((data.summary.dbUsedMB / data.summary.dbSizeMB) * 100).toFixed(1)}% used`}
        />
      </div>

      {/* Health Status Cards */}
      <div className="grid grid-cols-5 gap-4">
        {Object.entries(data.healthMetrics).map(([key, metric]) => (
          <div key={key} className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-xl p-4 hover:border-cyan-500/30 transition-all">
            <div className="flex items-center justify-between mb-3">
              <span className="text-slate-400 text-sm capitalize">{key.replace(/([A-Z])/g, ' $1').trim()}</span>
              <StatusBadge status={metric.status} size="sm" />
            </div>
            <div className="text-xl font-bold text-white">
              {metric.compliance ? `${metric.compliance}%` : 
               metric.avgUsage ? `${metric.avgUsage}%` : 
               metric.latency ? `${metric.latency}ms` : 
               metric.successRate ? `${metric.successRate}%` :
               metric.syncPercentage ? `${metric.syncPercentage}%` : '-'}
            </div>
            <div className="text-slate-500 text-xs mt-1">{metric.lastCheck || 'Real-time'}</div>
          </div>
        ))}
      </div>

      {/* Main Content Grid */}
      <div className="grid grid-cols-3 gap-6">
        {/* Reachability Status */}
        <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-xl p-6">
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
            <Activity className="w-5 h-5 text-cyan-400" />
            Server Reachability
          </h3>
          <div className="flex items-center justify-center mb-4">
            <div className="relative">
              <ProgressRing progress={data.reachability.percentage} size={120} color={data.reachability.percentage < 95 ? 'amber' : 'emerald'} />
              <div className="absolute inset-0 flex items-center justify-center">
                <div className="text-center">
                  <div className="text-2xl font-bold text-white">{data.reachability.percentage}%</div>
                  <div className="text-xs text-slate-400">Online</div>
                </div>
              </div>
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3 text-center">
            <div className="bg-emerald-500/10 rounded-lg p-3">
              <div className="text-xl font-bold text-emerald-400">{data.reachability.online}</div>
              <div className="text-xs text-slate-400">Online</div>
            </div>
            <div className="bg-red-500/10 rounded-lg p-3">
              <div className="text-xl font-bold text-red-400">{data.reachability.offline}</div>
              <div className="text-xs text-slate-400">Offline</div>
            </div>
          </div>
          {data.reachability.unreachableServers.length > 0 && (
            <div className="mt-4 pt-4 border-t border-slate-700/50">
              <p className="text-sm text-slate-400 mb-2">Unreachable Servers:</p>
              {data.reachability.unreachableServers.map(s => (
                <div key={s} className="flex items-center gap-2 text-sm text-red-400 mb-1">
                  <XCircle className="w-4 h-4" />
                  {s}
                </div>
              ))}
            </div>
          )}
        </div>

        {/* Failed Jobs */}
        <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-xl p-6">
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
            <AlertTriangle className="w-5 h-5 text-amber-400" />
            Failed Jobs (24h)
          </h3>
          <div className="space-y-3 max-h-80 overflow-y-auto">
            {data.failedJobs.map((job, i) => (
              <div key={i} className="bg-slate-900/50 rounded-lg p-3 border border-slate-700/30">
                <div className="flex items-start justify-between mb-1">
                  <span className="text-sm font-medium text-white truncate flex-1 mr-2">{job.name}</span>
                  <span className="text-xs text-slate-500 whitespace-nowrap">{job.time}</span>
                </div>
                <p className="text-xs text-red-400 truncate">{job.error}</p>
                <div className="flex items-center gap-2 mt-2">
                  <span className="text-xs bg-red-500/20 text-red-400 px-2 py-0.5 rounded">{job.count} failures</span>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Recent Alerts */}
        <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-xl p-6">
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
            <Bell className="w-5 h-5 text-cyan-400" />
            Recent Alerts
          </h3>
          <div className="space-y-3">
            {data.recentAlerts.map((alert, i) => (
              <div key={i} className={`rounded-lg p-3 border ${
                alert.type === 'critical' ? 'bg-red-500/10 border-red-500/30' :
                alert.type === 'warning' ? 'bg-amber-500/10 border-amber-500/30' :
                'bg-slate-700/30 border-slate-600/30'
              }`}>
                <div className="flex items-start gap-3">
                  {alert.type === 'critical' ? <XCircle className="w-5 h-5 text-red-400 mt-0.5" /> :
                   alert.type === 'warning' ? <AlertTriangle className="w-5 h-5 text-amber-400 mt-0.5" /> :
                   <CheckCircle className="w-5 h-5 text-cyan-400 mt-0.5" />}
                  <div className="flex-1">
                    <p className="text-sm text-white">{alert.message}</p>
                    <div className="flex items-center gap-2 mt-1">
                      <span className="text-xs text-slate-500">{alert.time}</span>
                      <span className="text-xs text-slate-600">•</span>
                      <span className="text-xs text-slate-500">{alert.source}</span>
                    </div>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Job Categories and Schema Overview */}
      <div className="grid grid-cols-2 gap-6">
        {/* Job Schedule Distribution */}
        <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-xl p-6">
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
            <Calendar className="w-5 h-5 text-cyan-400" />
            Job Schedule Distribution
          </h3>
          <div className="space-y-3">
            {data.scheduleFrequency.map((item, i) => (
              <div key={i} className="flex items-center gap-4">
                <span className="text-sm text-slate-400 w-32">{item.type}</span>
                <div className="flex-1 h-6 bg-slate-700/50 rounded-full overflow-hidden">
                  <div 
                    className="h-full bg-gradient-to-r from-cyan-500 to-blue-500 rounded-full transition-all duration-500"
                    style={{ width: `${(item.count / 54) * 100}%` }}
                  />
                </div>
                <span className="text-sm font-medium text-white w-12 text-right">{item.count}</span>
              </div>
            ))}
          </div>
        </div>

        {/* Database Schema Overview */}
        <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-xl p-6">
          <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
            <Layers className="w-5 h-5 text-cyan-400" />
            Schema Overview
          </h3>
          <div className="grid grid-cols-2 gap-3">
            {data.schemas.slice(0, 6).map((schema, i) => (
              <div key={i} className="bg-slate-900/50 rounded-lg p-3 border border-slate-700/30">
                <div className="flex items-center justify-between mb-1">
                  <span className="text-sm font-medium text-cyan-400">{schema.name}</span>
                  <span className="text-xs text-slate-500">{schema.tables}T / {schema.procedures}P</span>
                </div>
                <p className="text-xs text-slate-500 truncate">{schema.purpose}</p>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Top Tables by Size */}
      <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-xl p-6">
        <h3 className="text-lg font-semibold text-white mb-4 flex items-center gap-2">
          <TrendingUp className="w-5 h-5 text-cyan-400" />
          Top Tables by Size
        </h3>
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="text-left text-sm text-slate-400 border-b border-slate-700/50">
                <th className="pb-3 font-medium">Schema</th>
                <th className="pb-3 font-medium">Table Name</th>
                <th className="pb-3 font-medium text-right">Row Count</th>
                <th className="pb-3 font-medium text-right">Size (MB)</th>
                <th className="pb-3 font-medium">Usage</th>
              </tr>
            </thead>
            <tbody className="text-sm">
              {data.topTables.map((table, i) => (
                <tr key={i} className="border-b border-slate-700/30 hover:bg-slate-700/20">
                  <td className="py-3 text-cyan-400 font-medium">{table.schema}</td>
                  <td className="py-3 text-white">{table.name}</td>
                  <td className="py-3 text-right text-slate-300">{table.rows.toLocaleString()}</td>
                  <td className="py-3 text-right text-slate-300">{table.sizeMB.toLocaleString()}</td>
                  <td className="py-3">
                    <div className="w-24 h-2 bg-slate-700/50 rounded-full overflow-hidden">
                      <div 
                        className="h-full bg-gradient-to-r from-cyan-500 to-blue-500 rounded-full"
                        style={{ width: `${Math.min((table.sizeMB / 10902.77) * 100, 100)}%` }}
                      />
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

const ServersTab = ({ data }) => {
  const [filter, setFilter] = useState('all');
  
  const allServers = [...data.servers.prod.map(s => ({...s, env: 'PROD'})), ...data.servers.nonProd.map(s => ({...s, env: 'NONPROD'}))];
  const filteredServers = filter === 'all' ? allServers : 
    filter === 'prod' ? allServers.filter(s => s.env === 'PROD') :
    filter === 'nonprod' ? allServers.filter(s => s.env === 'NONPROD') :
    filter === 'offline' ? allServers.filter(s => s.status === 'offline') : allServers;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-2xl font-bold text-white">Server Inventory</h2>
        <div className="flex items-center gap-2">
          {['all', 'prod', 'nonprod', 'offline'].map(f => (
            <button
              key={f}
              onClick={() => setFilter(f)}
              className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
                filter === f 
                  ? 'bg-cyan-500/20 text-cyan-400 border border-cyan-500/30' 
                  : 'bg-slate-800/50 text-slate-400 hover:text-white border border-slate-700/50'
              }`}
            >
              {f.charAt(0).toUpperCase() + f.slice(1)} {f === 'all' ? `(${allServers.length})` : f === 'offline' ? `(${allServers.filter(s => s.status === 'offline').length})` : ''}
            </button>
          ))}
        </div>
      </div>

      <div className="grid grid-cols-3 gap-4">
        {filteredServers.map((server, i) => (
          <div key={i} className={`bg-slate-800/50 backdrop-blur-sm border rounded-xl p-5 transition-all hover:scale-[1.02] ${
            server.status === 'offline' ? 'border-red-500/30' : 'border-slate-700/50 hover:border-cyan-500/30'
          }`}>
            <div className="flex items-start justify-between mb-4">
              <div>
                <h3 className="text-white font-semibold">{server.name}</h3>
                <span className={`text-xs px-2 py-0.5 rounded mt-1 inline-block ${
                  server.env === 'PROD' ? 'bg-blue-500/20 text-blue-400' : 'bg-purple-500/20 text-purple-400'
                }`}>{server.env}</span>
              </div>
              <StatusBadge status={server.status} size="sm" />
            </div>
            
            {server.status === 'online' ? (
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <span className="text-sm text-slate-400 flex items-center gap-2">
                    <Cpu className="w-4 h-4" /> CPU
                  </span>
                  <div className="flex items-center gap-2">
                    <div className="w-20 h-2 bg-slate-700/50 rounded-full overflow-hidden">
                      <div className={`h-full rounded-full ${server.cpu > 80 ? 'bg-red-500' : server.cpu > 60 ? 'bg-amber-500' : 'bg-emerald-500'}`} style={{width: `${server.cpu}%`}} />
                    </div>
                    <span className="text-sm text-white w-10 text-right">{server.cpu}%</span>
                  </div>
                </div>
                <div className="flex items-center justify-between">
                  <span className="text-sm text-slate-400 flex items-center gap-2">
                    <MemoryStick className="w-4 h-4" /> Memory
                  </span>
                  <div className="flex items-center gap-2">
                    <div className="w-20 h-2 bg-slate-700/50 rounded-full overflow-hidden">
                      <div className={`h-full rounded-full ${server.memory > 85 ? 'bg-red-500' : server.memory > 70 ? 'bg-amber-500' : 'bg-emerald-500'}`} style={{width: `${server.memory}%`}} />
                    </div>
                    <span className="text-sm text-white w-10 text-right">{server.memory}%</span>
                  </div>
                </div>
                <div className="flex items-center justify-between pt-2 border-t border-slate-700/30">
                  <span className="text-sm text-slate-400 flex items-center gap-2">
                    <Database className="w-4 h-4" /> Databases
                  </span>
                  <span className="text-sm text-white">{server.databases}</span>
                </div>
              </div>
            ) : (
              <div className="flex items-center justify-center py-4">
                <div className="text-center">
                  <XCircle className="w-8 h-8 text-red-400 mx-auto mb-2" />
                  <p className="text-sm text-red-400">Server Unreachable</p>
                  <p className="text-xs text-slate-500 mt-1">Login failed for DBAOpsCollector</p>
                </div>
              </div>
            )}
          </div>
        ))}
      </div>
    </div>
  );
};

const JobsTab = ({ data }) => {
  const [view, setView] = useState('failed');
  
  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-2xl font-bold text-white">SQL Agent Jobs</h2>
        <div className="flex items-center gap-2">
          <button
            onClick={() => setView('failed')}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
              view === 'failed' ? 'bg-red-500/20 text-red-400 border border-red-500/30' : 'bg-slate-800/50 text-slate-400 border border-slate-700/50'
            }`}
          >
            <AlertTriangle className="w-4 h-4 inline mr-2" />
            Failed ({data.failedJobs.length})
          </button>
          <button
            onClick={() => setView('categories')}
            className={`px-4 py-2 rounded-lg text-sm font-medium transition-all ${
              view === 'categories' ? 'bg-cyan-500/20 text-cyan-400 border border-cyan-500/30' : 'bg-slate-800/50 text-slate-400 border border-slate-700/50'
            }`}
          >
            <Layers className="w-4 h-4 inline mr-2" />
            Categories
          </button>
        </div>
      </div>

      {view === 'failed' && (
        <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-xl overflow-hidden">
          <table className="w-full">
            <thead>
              <tr className="text-left text-sm text-slate-400 border-b border-slate-700/50 bg-slate-900/50">
                <th className="p-4 font-medium">Job Name</th>
                <th className="p-4 font-medium">Error Message</th>
                <th className="p-4 font-medium">Last Failed</th>
                <th className="p-4 font-medium text-center">Failures</th>
                <th className="p-4 font-medium">Actions</th>
              </tr>
            </thead>
            <tbody className="text-sm">
              {data.failedJobs.map((job, i) => (
                <tr key={i} className="border-b border-slate-700/30 hover:bg-slate-700/20">
                  <td className="p-4 text-white font-medium">{job.name}</td>
                  <td className="p-4 text-red-400 max-w-md truncate">{job.error}</td>
                  <td className="p-4 text-slate-400">{job.time}</td>
                  <td className="p-4 text-center">
                    <span className="bg-red-500/20 text-red-400 px-3 py-1 rounded-full text-xs font-medium">{job.count}</span>
                  </td>
                  <td className="p-4">
                    <div className="flex items-center gap-2">
                      <button className="p-2 rounded-lg bg-slate-700/50 hover:bg-cyan-500/20 text-slate-400 hover:text-cyan-400 transition-colors">
                        <Play className="w-4 h-4" />
                      </button>
                      <button className="p-2 rounded-lg bg-slate-700/50 hover:bg-slate-600/50 text-slate-400 hover:text-white transition-colors">
                        <Terminal className="w-4 h-4" />
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {view === 'categories' && (
        <div className="grid grid-cols-2 gap-6">
          <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-xl p-6">
            <h3 className="text-lg font-semibold text-white mb-4">Jobs by Category</h3>
            <div className="space-y-3">
              {data.jobCategories.map((cat, i) => (
                <div key={i} className="flex items-center justify-between p-3 bg-slate-900/50 rounded-lg">
                  <span className="text-sm text-white">{cat.name}</span>
                  <div className="flex items-center gap-3">
                    <span className="text-sm text-emerald-400">{cat.enabled} enabled</span>
                    <span className="text-sm text-slate-500">/ {cat.count} total</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
          
          <div className="bg-slate-800/50 backdrop-blur-sm border border-slate-700/50 rounded-xl p-6">
            <h3 className="text-lg font-semibold text-white mb-4">Schedule Distribution</h3>
            <div className="space-y-3">
              {data.scheduleFrequency.map((item, i) => (
                <div key={i} className="flex items-center gap-4">
                  <span className="text-sm text-slate-400 w-32">{item.type}</span>
                  <div className="flex-1 h-8 bg-slate-700/50 rounded-lg overflow-hidden relative">
                    <div 
                      className="h-full bg-gradient-to-r from-cyan-500/80 to-blue-500/80 rounded-lg transition-all duration-500 flex items-center justify-end pr-3"
                      style={{ width: `${(item.count / 54) * 100}%` }}
                    >
                      <span className="text-xs font-medium text-white">{item.count}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default function DBAOpsDashboard() {
  const [activeTab, setActiveTab] = useState('dashboard');
  const [lastUpdate, setLastUpdate] = useState(new Date().toLocaleTimeString());
  const [data, setData] = useState(mockData);

  const handleRefresh = () => {
    setLastUpdate(new Date().toLocaleTimeString());
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex">
      {/* Background Pattern */}
      <div className="fixed inset-0 opacity-30">
        <div className="absolute inset-0" style={{
          backgroundImage: `radial-gradient(circle at 1px 1px, rgba(6, 182, 212, 0.15) 1px, transparent 0)`,
          backgroundSize: '40px 40px'
        }} />
      </div>
      
      <Sidebar activeTab={activeTab} setActiveTab={setActiveTab} />
      
      <div className="flex-1 flex flex-col relative">
        <Header onRefresh={handleRefresh} lastUpdate={lastUpdate} />
        
        <main className="flex-1 overflow-auto p-6">
          {activeTab === 'dashboard' && <DashboardTab data={data} />}
          {activeTab === 'servers' && <ServersTab data={data} />}
          {activeTab === 'jobs' && <JobsTab data={data} />}
          {activeTab === 'databases' && (
            <div className="flex items-center justify-center h-full">
              <div className="text-center">
                <Database className="w-16 h-16 text-slate-600 mx-auto mb-4" />
                <h2 className="text-xl font-semibold text-white mb-2">Database Browser</h2>
                <p className="text-slate-400">Coming soon - Browse all 1,230 databases</p>
              </div>
            </div>
          )}
          {activeTab === 'alerts' && (
            <div className="flex items-center justify-center h-full">
              <div className="text-center">
                <Bell className="w-16 h-16 text-slate-600 mx-auto mb-4" />
                <h2 className="text-xl font-semibold text-white mb-2">Alert Center</h2>
                <p className="text-slate-400">Configure and view all alerts</p>
              </div>
            </div>
          )}
          {activeTab === 'reports' && (
            <div className="flex items-center justify-center h-full">
              <div className="text-center">
                <FileText className="w-16 h-16 text-slate-600 mx-auto mb-4" />
                <h2 className="text-xl font-semibold text-white mb-2">Reports</h2>
                <p className="text-slate-400">Daily, weekly, and compliance reports</p>
              </div>
            </div>
          )}
          {activeTab === 'settings' && (
            <div className="flex items-center justify-center h-full">
              <div className="text-center">
                <Settings className="w-16 h-16 text-slate-600 mx-auto mb-4" />
                <h2 className="text-xl font-semibold text-white mb-2">Settings</h2>
                <p className="text-slate-400">Configure thresholds, notifications, and more</p>
              </div>
            </div>
          )}
        </main>
      </div>
    </div>
  );
}
