import React, { useState, useEffect, useCallback } from 'react';
import { LineChart, Line, BarChart, Bar, PieChart, Pie, Cell, AreaChart, Area,
  XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { Activity, Clock, Database, AlertTriangle, CheckCircle, XCircle, 
  TrendingUp, TrendingDown, Search, Filter, RefreshCw, Settings, Play, 
  Pause, RotateCcw, FileText, ChevronRight, Layers, Zap, Shield } from 'lucide-react';

// Mock data matching BigQuery Jobs API structure
const MOCK_JOBS = [
  { job_id: "daily_customer_etl", state: "RUNNING", creationTime: 1771059781456, startTime: 1771059782203, endTime: null, totalBytesProcessed: 1073741824, totalSlotMs: 12500, errorResult: null, pipeline: "customer-data" },
  { job_id: "hourly_sales_agg", state: "DONE", creationTime: 1771056181456, startTime: 1771056182203, endTime: 1771056242324, totalBytesProcessed: 524288000, totalSlotMs: 8200, errorResult: null, pipeline: "sales-analytics" },
  { job_id: "daily_inventory_sync", state: "FAILED", creationTime: 1771052581456, startTime: 1771052582203, endTime: 1771052642324, totalBytesProcessed: 0, totalSlotMs: 1500, errorResult: { message: "Table not found: inventory.raw_stock" }, pipeline: "inventory" },
  { job_id: "weekly_user_cohort", state: "DONE", creationTime: 1771048981456, startTime: 1771048982203, endTime: 1771049282324, totalBytesProcessed: 2147483648, totalSlotMs: 45000, errorResult: null, pipeline: "user-analytics" },
  { job_id: "realtime_clickstream", state: "RUNNING", creationTime: 1771063381456, startTime: 1771063382203, endTime: null, totalBytesProcessed: 268435456, totalSlotMs: 3200, errorResult: null, pipeline: "clickstream" },
  { job_id: "daily_fraud_detect", state: "PENDING", creationTime: 1771066981456, startTime: null, endTime: null, totalBytesProcessed: 0, totalSlotMs: 0, errorResult: null, pipeline: "fraud-prevention" },
  { job_id: "hourly_metrics_rollup", state: "DONE", creationTime: 1771059781456, startTime: 1771059782203, endTime: 1771059842324, totalBytesProcessed: 134217728, totalSlotMs: 5600, errorResult: null, pipeline: "platform-metrics" },
  { job_id: "daily_product_catalog", state: "DONE", creationTime: 1771056181456, startTime: 1771056182203, endTime: 1771056302324, totalBytesProcessed: 805306368, totalSlotMs: 15200, errorResult: null, pipeline: "product-data" },
];

const MOCK_TIMELINE_DATA = [
  { time: "00:00", jobs: 12, failed: 1, bytes: 1.2 },
  { time: "04:00", jobs: 18, failed: 0, bytes: 2.1 },
  { time: "08:00", jobs: 24, failed: 2, bytes: 3.4 },
  { time: "12:00", jobs: 31, failed: 1, bytes: 4.2 },
  { time: "16:00", jobs: 28, failed: 0, bytes: 3.8 },
  { time: "20:00", jobs: 22, failed: 1, bytes: 2.9 },
];

const MOCK_STATUS_DISTRIBUTION = [
  { name: "Running", value: 2, color: "#3b82f6" },
  { name: "Success", value: 4, color: "#22c55e" },
  { name: "Failed", value: 1, color: "#ef4444" },
  { name: "Pending", value: 1, color: "#f59e0b" },
];

const MOCK_QUALITY_METRICS = {
  completeness: 98.2,
  accuracy: 97.5,
  timeliness: 99.1,
  nullRate: 0.3,
  duplicateRate: 0.1,
  schemaViolations: 0,
};

const formatBytes = (bytes: number): string => {
  if (bytes === 0) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

const formatDuration = (start: number, end: number | null): string => {
  const endTime = end || Date.now();
  const diff = endTime - start;
  const hours = Math.floor(diff / 3600000);
  const minutes = Math.floor((diff % 3600000) / 60000);
  const seconds = Math.floor((diff % 60000) / 1000);
  if (hours > 0) return `${hours}h ${minutes}m`;
  if (minutes > 0) return `${minutes}m ${seconds}s`;
  return `${seconds}s`;
};

const formatTime = (timestamp: number): string => {
  return new Date(timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
};

const formatRelativeTime = (timestamp: number): string => {
  const diff = Date.now() - timestamp;
  const hours = Math.floor(diff / 3600000);
  if (hours < 1) return "Just now";
  if (hours < 24) return `${hours}h ago`;
  return `${Math.floor(hours / 24)}d ago`;
};

const getStatusColor = (state: string): string => {
  switch (state) {
    case "RUNNING": return "#3b82f6";
    case "DONE": return "#22c55e";
    case "FAILED": return "#ef4444";
    case "PENDING": return "#f59e0b";
    default: return "#64748b";
  }
};

export default function App() {
  const [jobs, setJobs] = useState(MOCK_JOBS);
  const [selectedJob, setSelectedJob] = useState<any>(null);
  const [statusFilter, setStatusFilter] = useState("All");
  const [searchQuery, setSearchQuery] = useState("");
  const [sortColumn, setSortColumn] = useState("creationTime");
  const [sortDirection, setSortDirection] = useState<"asc" | "desc">("desc");
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [lastUpdated, setLastUpdated] = useState(new Date());

  const healthScore = 94;
  const jobsCount24h = 156;
  const throughputTB = 2.4;
  const qualityScore = 98.2;

  useEffect(() => {
    if (!autoRefresh) return;
    const interval = setInterval(() => {
      setLastUpdated(new Date());
    }, 30000);
    return () => clearInterval(interval);
  }, [autoRefresh]);

  const filteredJobs = jobs.filter(job => {
    const matchesStatus = statusFilter === "All" || job.state === statusFilter;
    const matchesSearch = job.job_id.toLowerCase().includes(searchQuery.toLowerCase()) ||
                          job.pipeline.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesStatus && matchesSearch;
  });

  const sortedJobs = [...filteredJobs].sort((a, b) => {
    const aVal = a[sortColumn as keyof typeof a];
    const bVal = b[sortColumn as keyof typeof b];
    if (aVal === null || aVal === undefined) return 1;
    if (bVal === null || bVal === undefined) return -1;
    const comparison = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
    return sortDirection === "asc" ? comparison : -comparison;
  });

  const handleSort = (column: string) => {
    if (sortColumn === column) {
      setSortDirection(sortDirection === "asc" ? "desc" : "asc");
    } else {
      setSortColumn(column);
      setSortDirection("desc");
    }
  };

  const getStatusBadgeClass = (state: string) => {
    const base = "status-badge inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-semibold uppercase";
    switch (state) {
      case "RUNNING": return `${base} bg-blue-500/15 text-blue-500 border border-blue-500/30`;
      case "DONE": return `${base} bg-green-500/15 text-green-500 border border-green-500/30`;
      case "FAILED": return `${base} bg-red-500/15 text-red-500 border border-red-500/30`;
      case "PENDING": return `${base} bg-amber-500/15 text-amber-500 border border-amber-500/30`;
      default: return `${base} bg-slate-500/15 text-slate-500 border border-slate-500/30`;
    }
  };

  return (
    <div className="min-h-screen bg-[#0a0e1a] text-slate-200 font-sans">
      {/* Header */}
      <header className="sticky top-0 z-100 bg-[#0a0e1a] border-b border-white/[0.08] px-6 py-4 flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="w-8 h-8 rounded-lg bg-gradient-to-br from-blue-500 to-cyan-400 flex items-center justify-center">
            <Activity size={18} className="text-white" />
          </div>
          <h1 className="text-xl font-semibold text-white">Pipeline Monitor</h1>
        </div>
        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2 text-sm text-slate-400">
            <RefreshCw size={14} className={autoRefresh ? "animate-spin text-green-500" : ""} />
            <span>Auto-refresh: {autoRefresh ? "ON" : "OFF"}</span>
            <button
              onClick={() => setAutoRefresh(!autoRefresh)}
              className={`w-11 h-6 rounded-full relative transition-colors ${autoRefresh ? 'bg-green-500' : 'bg-slate-600'}`}
            >
              <div className={`absolute top-1 w-4 h-4 bg-white rounded-full transition-transform ${autoRefresh ? 'left-6' : 'left-1'}`} />
            </button>
          </div>
          <button className="p-2 hover:bg-white/[0.06] rounded-lg transition-colors">
            <Settings size={18} className="text-slate-400" />
          </button>
        </div>
      </header>

      {/* KPI Row */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 px-6 py-6">
        {/* Health Score */}
        <div className="glass p-5 relative overflow-hidden border-l-4 border-l-green-500">
          <div className="flex items-center justify-between mb-3">
            <span className="text-xs uppercase tracking-wider text-slate-400">Health Score</span>
            <CheckCircle size={16} className="text-green-500" />
          </div>
          <div className="flex items-center gap-4">
            <div className="relative w-16 h-16">
              <svg className="w-full h-full transform -rotate-90">
                <circle cx="32" cy="32" r="28" fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="6" />
                <circle cx="32" cy="32" r="28" fill="none" stroke="#22c55e" strokeWidth="6"
                  strokeDasharray={176} strokeDashoffset={176 - (176 * healthScore) / 100}
                  strokeLinecap="round" className="transition-all duration-1000" />
              </svg>
              <span className="absolute inset-0 flex items-center justify-center text-lg font-bold text-white">
                {healthScore}%
              </span>
            </div>
            <div>
              <div className="text-2xl font-bold text-white">Excellent</div>
              <div className="text-xs text-green-400 mt-1 flex items-center gap-1">
                <TrendingUp size={12} /> +2% from yesterday
              </div>
            </div>
          </div>
        </div>

        {/* Jobs 24H */}
        <div className="glass p-5 relative overflow-hidden border-l-4 border-l-blue-500">
          <div className="flex items-center justify-between mb-3">
            <span className="text-xs uppercase tracking-wider text-slate-400">Jobs (24h)</span>
            <Layers size={16} className="text-blue-500" />
          </div>
          <div className="text-3xl font-bold text-white mb-2">{jobsCount24h}</div>
          <div className="text-xs text-slate-400 flex items-center gap-1">
            <TrendingUp size={12} className="text-green-400" /> +12 vs previous 24h
          </div>
        </div>

        {/* Throughput */}
        <div className="glass p-5 relative overflow-hidden border-l-4 border-l-cyan-500">
          <div className="flex items-center justify-between mb-3">
            <span className="text-xs uppercase tracking-wider text-slate-400">Throughput</span>
            <Zap size={16} className="text-cyan-500" />
          </div>
          <div className="text-3xl font-bold text-white mb-2">{throughputTB} TB/d</div>
          <div className="text-xs text-green-400 flex items-center gap-1">
            <TrendingUp size={12} /> +8.5% from average
          </div>
        </div>

        {/* Data Quality */}
        <div className="glass p-5 relative overflow-hidden border-l-4 border-l-purple-500">
          <div className="flex items-center justify-between mb-3">
            <span className="text-xs uppercase tracking-wider text-slate-400">Data Quality</span>
            <Shield size={16} className="text-purple-500" />
          </div>
          <div className="text-3xl font-bold text-white mb-2">{qualityScore}%</div>
          <div className="text-xs text-slate-400">
            Threshold: 95% ✓
          </div>
        </div>
      </div>

      {/* Charts Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-4 px-6 pb-6">
        {/* Timeline Chart */}
        <div className="glass p-5 min-h-[280px]">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-white flex items-center gap-2">
              <Activity size={16} className="text-blue-400" />
              Pipeline Timeline
            </h3>
            <div className="flex gap-3 text-xs text-slate-400">
              <span className="flex items-center gap-1"><div className="w-2 h-2 rounded-full bg-blue-500" /> Jobs</span>
              <span className="flex items-center gap-1"><div className="w-2 h-2 rounded-full bg-red-500" /> Failed</span>
            </div>
          </div>
          <ResponsiveContainer width="100%" height={220}>
            <AreaChart data={MOCK_TIMELINE_DATA}>
              <defs>
                <linearGradient id="colorJobs" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3}/>
                  <stop offset="95%" stopColor="#3b82f6" stopOpacity={0}/>
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.06)" />
              <XAxis dataKey="time" stroke="#64748b" fontSize={12} />
              <YAxis stroke="#64748b" fontSize={12} />
              <Tooltip
                contentStyle={{ backgroundColor: 'rgba(15,23,42,0.95)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
                labelStyle={{ color: '#94a3b8' }}
              />
              <Area type="monotone" dataKey="jobs" stroke="#3b82f6" fillOpacity={1} fill="url(#colorJobs)" />
              <Line type="monotone" dataKey="failed" stroke="#ef4444" strokeWidth={2} dot={{ r: 4 }} />
            </AreaChart>
          </ResponsiveContainer>
        </div>

        {/* Status Distribution */}
        <div className="glass p-5 min-h-[280px]">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-sm font-semibold text-white flex items-center gap-2">
              <Database size={16} className="text-purple-400" />
              Job Distribution
            </h3>
          </div>
          <div className="flex items-center gap-6">
            <ResponsiveContainer width="50%" height={200}>
              <PieChart>
                <Pie
                  data={MOCK_STATUS_DISTRIBUTION}
                  cx="50%"
                  cy="50%"
                  innerRadius={50}
                  outerRadius={80}
                  paddingAngle={2}
                  dataKey="value"
                >
                  {MOCK_STATUS_DISTRIBUTION.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip
                  contentStyle={{ backgroundColor: 'rgba(15,23,42,0.95)', border: '1px solid rgba(255,255,255,0.1)', borderRadius: '8px' }}
                />
              </PieChart>
            </ResponsiveContainer>
            <div className="flex-1 space-y-3">
              {MOCK_STATUS_DISTRIBUTION.map((item) => (
                <div key={item.name} className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <div className="w-3 h-3 rounded-full" style={{ backgroundColor: item.color }} />
                    <span className="text-sm text-slate-300">{item.name}</span>
                  </div>
                  <span className="text-sm font-semibold text-white">{item.value}</span>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* Filter Bar */}
      <div className="flex items-center justify-between px-6 py-3 border-b border-white/[0.08]">
        <div className="flex gap-2">
          {["All", "RUNNING", "DONE", "FAILED", "PENDING"].map((status) => (
            <button
              key={status}
              onClick={() => setStatusFilter(status)}
              className={`px-3 py-1.5 rounded-full text-xs font-medium transition-all ${
                statusFilter === status
                  ? 'bg-blue-500 text-white'
                  : 'bg-white/[0.03] text-slate-400 border border-white/[0.08] hover:bg-white/[0.06]'
              }`}
            >
              {status}
            </button>
          ))}
        </div>
        <div className="relative">
          <Search size={14} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <input
            type="text"
            placeholder="Search jobs..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-9 pr-4 py-1.5 bg-white/[0.03] border border-white/[0.08] rounded-lg text-sm text-white placeholder-slate-400 focus:outline-none focus:border-blue-500 w-60"
          />
        </div>
      </div>

      {/* Jobs Table */}
      <div className="px-6 py-4 overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b border-white/[0.08]">
              <th className="text-left py-3 px-4 text-xs uppercase tracking-wider text-slate-400 font-semibold cursor-pointer hover:text-white" onClick={() => handleSort('job_id')}>
                Job Name {sortColumn === 'job_id' && (sortDirection === 'asc' ? '↑' : '↓')}
              </th>
              <th className="text-left py-3 px-4 text-xs uppercase tracking-wider text-slate-400 font-semibold cursor-pointer hover:text-white" onClick={() => handleSort('state')}>
                Status {sortColumn === 'state' && (sortDirection === 'asc' ? '↑' : '↓')}
              </th>
              <th className="text-left py-3 px-4 text-xs uppercase tracking-wider text-slate-400 font-semibold cursor-pointer hover:text-white" onClick={() => handleSort('startTime')}>
                Duration {sortColumn === 'startTime' && (sortDirection === 'asc' ? '↑' : '↓')}
              </th>
              <th className="text-left py-3 px-4 text-xs uppercase tracking-wider text-slate-400 font-semibold cursor-pointer hover:text-white" onClick={() => handleSort('totalBytesProcessed')}>
                Records {sortColumn === 'totalBytesProcessed' && (sortDirection === 'asc' ? '↑' : '↓')}
              </th>
              <th className="text-left py-3 px-4 text-xs uppercase tracking-wider text-slate-400 font-semibold">
                Quality
              </th>
              <th className="text-left py-3 px-4 text-xs uppercase tracking-wider text-slate-400 font-semibold cursor-pointer hover:text-white" onClick={() => handleSort('creationTime')}>
                Started {sortColumn === 'creationTime' && (sortDirection === 'asc' ? '↑' : '↓')}
              </th>
              <th className="py-3 px-4"></th>
            </tr>
          </thead>
          <tbody>
            {sortedJobs.map((job) => (
              <tr
                key={job.job_id}
                onClick={() => setSelectedJob(job)}
                className={`border-b border-white/[0.06] cursor-pointer transition-colors ${
                  selectedJob?.job_id === job.job_id ? 'bg-white/[0.06]' : 'hover:bg-white/[0.03]'
                }`}
              >
                <td className="py-3 px-4">
                  <div className="font-mono text-white">{job.job_id}</div>
                  <div className="text-xs text-slate-400">{job.pipeline}</div>
                </td>
                <td className="py-3 px-4">
                  <span className={getStatusBadgeClass(job.state)}>
                    {job.state === "RUNNING" && <div className="w-1.5 h-1.5 rounded-full bg-current animate-pulse" />}
                    {job.state}
                  </span>
                </td>
                <td className="py-3 px-4 text-slate-300">
                  {job.startTime ? formatDuration(job.startTime, job.endTime) : '-'}
                </td>
                <td className="py-3 px-4 text-slate-300">
                  {formatBytes(job.totalBytesProcessed)}
                </td>
                <td className="py-3 px-4">
                  <div className="flex items-center gap-2">
                    <div className="w-16 h-1.5 bg-white/[0.06] rounded-full overflow-hidden">
                      <div className="h-full bg-green-500 rounded-full" style={{ width: `${95 + Math.random() * 5}%` }} />
                    </div>
                    <span className="text-xs text-slate-400">{(95 + Math.random() * 5).toFixed(1)}%</span>
                  </div>
                </td>
                <td className="py-3 px-4 text-slate-300">
                  <div className="text-white">{formatTime(job.creationTime)}</div>
                  <div className="text-xs text-slate-400">{formatRelativeTime(job.creationTime)}</div>
                </td>
                <td className="py-3 px-4">
                  <ChevronRight size={16} className="text-slate-400" />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Details Panel */}
      {selectedJob && (
        <div className="fixed inset-0 z-200" onClick={() => setSelectedJob(null)}>
          <div className="absolute inset-0 bg-black/50 backdrop-blur-sm" />
          <div
            className="absolute right-0 top-0 h-full w-full max-w-md bg-[#0f172a] border-l border-white/[0.1] p-6 overflow-y-auto"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-start justify-between mb-6">
              <div>
                <h2 className="text-lg font-semibold text-white font-mono">{selectedJob.job_id}</h2>
                <div className="text-sm text-slate-400 mt-1">{selectedJob.pipeline}</div>
              </div>
              <button onClick={() => setSelectedJob(null)} className="p-1 hover:bg-white/[0.06] rounded-lg">
                <XCircle size={20} className="text-slate-400" />
              </button>
            </div>

            <div className="mb-6">
              <span className={getStatusBadgeClass(selectedJob.state)}>
                {selectedJob.state === "RUNNING" && <div className="w-1.5 h-1.5 rounded-full bg-current animate-pulse" />}
                {selectedJob.state}
              </span>
              {selectedJob.startTime && (
                <div className="mt-3 text-sm text-slate-400">
                  Duration: <span className="text-white font-medium">{formatDuration(selectedJob.startTime, selectedJob.endTime)}</span>
                </div>
              )}
            </div>

            {/* Pipeline Stages */}
            <div className="py-4 border-y border-white/[0.08] mb-6">
              <div className="flex items-center">
                <div className="flex flex-col items-center flex-1">
                  <div className={`w-3 h-3 rounded-full border-2 ${
                    selectedJob.startTime ? 'bg-green-500 border-green-500' : 'bg-slate-600 border-slate-500'
                  }`} />
                  <span className="text-xs text-slate-400 mt-2 uppercase">Source</span>
                </div>
                <div className={`flex-1 h-0.5 ${
                  selectedJob.startTime ? 'bg-green-500' : 'bg-slate-600'
                }`} />
                <div className="flex flex-col items-center flex-1">
                  <div className={`w-3 h-3 rounded-full border-2 ${
                    selectedJob.state === 'RUNNING' ? 'bg-blue-500 border-blue-500 animate-pulse' :
                    selectedJob.state === 'DONE' ? 'bg-green-500 border-green-500' :
                    'bg-slate-600 border-slate-500'
                  }`} />
                  <span className="text-xs text-slate-400 mt-2 uppercase">Transform</span>
                </div>
                <div className={`flex-1 h-0.5 ${
                  selectedJob.state === 'DONE' ? 'bg-green-500' : 'bg-slate-600'
                }`} />
                <div className="flex flex-col items-center flex-1">
                  <div className={`w-3 h-3 rounded-full border-2 ${
                    selectedJob.state === 'DONE' ? 'bg-green-500 border-green-500' : 'bg-slate-600 border-slate-500'
                  }`} />
                  <span className="text-xs text-slate-400 mt-2 uppercase">Load</span>
                </div>
              </div>
            </div>

            {/* Quality Metrics */}
            <div className="mb-6">
              <h3 className="text-sm font-semibold text-white mb-3 flex items-center gap-2">
                <Shield size={14} className="text-purple-400" />
                Data Quality
              </h3>
              <div className="grid grid-cols-3 gap-3">
                <div className="bg-white/[0.03] rounded-lg p-3 text-center">
                  <div className="text-lg font-bold text-white">{MOCK_QUALITY_METRICS.completeness}%</div>
                  <div className="text-xs text-slate-400 mt-1">Completeness</div>
                </div>
                <div className="bg-white/[0.03] rounded-lg p-3 text-center">
                  <div className="text-lg font-bold text-white">{MOCK_QUALITY_METRICS.nullRate}%</div>
                  <div className="text-xs text-slate-400 mt-1">Null Rate</div>
                </div>
                <div className="bg-white/[0.03] rounded-lg p-3 text-center">
                  <div className="text-lg font-bold text-white">{MOCK_QUALITY_METRICS.duplicateRate}%</div>
                  <div className="text-xs text-slate-400 mt-1">Duplicates</div>
                </div>
              </div>
            </div>

            {/* Error Message */}
            {selectedJob.errorResult && (
              <div className="mb-6 p-4 bg-red-500/10 border border-red-500/30 rounded-lg">
                <div className="flex items-start gap-3">
                  <AlertTriangle size={18} className="text-red-400 mt-0.5" />
                  <div>
                    <div className="text-sm font-semibold text-red-400 mb-1">Error</div>
                    <div className="text-sm text-red-300 font-mono">{selectedJob.errorResult.message}</div>
                  </div>
                </div>
              </div>
            )}

            {/* Stats */}
            <div className="mb-6 space-y-3">
              <div className="flex justify-between py-2 border-b border-white/[0.06]">
                <span className="text-sm text-slate-400">Bytes Processed</span>
                <span className="text-sm font-medium text-white">{formatBytes(selectedJob.totalBytesProcessed)}</span>
              </div>
              <div className="flex justify-between py-2 border-b border-white/[0.06]">
                <span className="text-sm text-slate-400">Compute (Slot-ms)</span>
                <span className="text-sm font-medium text-white">{selectedJob.totalSlotMs.toLocaleString()}</span>
              </div>
              <div className="flex justify-between py-2 border-b border-white/[0.06]">
                <span className="text-sm text-slate-400">Created</span>
                <span className="text-sm font-medium text-white">{formatTime(selectedJob.creationTime)}</span>
              </div>
            </div>

            {/* Action Buttons */}
            <div className="flex gap-2">
              <button className="flex-1 py-2.5 px-4 bg-blue-500 hover:bg-blue-600 text-white rounded-lg font-medium text-sm transition-colors flex items-center justify-center gap-2">
                <FileText size={14} /> View Logs
              </button>
              {selectedJob.state === 'FAILED' && (
                <button className="flex-1 py-2.5 px-4 bg-green-500/20 hover:bg-green-500/30 text-green-400 border border-green-500/30 rounded-lg font-medium text-sm transition-colors flex items-center justify-center gap-2">
                  <RotateCcw size={14} /> Retry
                </button>
              )}
              {selectedJob.state === 'RUNNING' && (
                <button className="flex-1 py-2.5 px-4 bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 border border-amber-500/30 rounded-lg font-medium text-sm transition-colors flex items-center justify-center gap-2">
                  <Pause size={14} /> Pause
                </button>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Footer */}
      <footer className="px-6 py-4 border-t border-white/[0.08] text-xs text-slate-500 flex items-center justify-between">
        <span>Last updated: {lastUpdated.toLocaleTimeString()}</span>
        <span className="flex items-center gap-2">
          <div className="w-2 h-2 rounded-full bg-green-500" />
          Connected to BigQuery
        </span>
      </footer>

      <style>{`
        .glass {
          background: rgba(255, 255, 255, 0.03);
          backdrop-filter: blur(12px);
          -webkit-backdrop-filter: blur(12px);
          border: 1px solid rgba(255, 255, 255, 0.08);
          border-radius: 16px;
        }
      `}</style>
    </div>
  );
}
