import { useState, useRef, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useLocation } from 'react-router-dom'
import { backupAPI, StoragePool, StorageVolume, CreateStoragePoolRequest } from '@/api/backup'
import { X } from 'lucide-react'

// Styles for checkbox and tree lines
const clientManagementStyles = `
  .status-dot {
    box-shadow: 0 0 6px currentColor;
  }
  .checkbox-custom {
    appearance: none;
    background-color: #1c2936;
    border: 1px solid #324d67;
    border-radius: 4px;
    width: 16px;
    height: 16px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
  }
  .checkbox-custom:checked {
    background-color: #137fec;
    border-color: #137fec;
  }
  .checkbox-custom:checked::after {
    content: '';
    width: 4px;
    height: 8px;
    border: solid white;
    border-width: 0 2px 2px 0;
    transform: rotate(45deg);
    margin-bottom: 2px;
  }
  .agent-item {
    position: relative;
  }
  .agent-item .tree-line-vertical {
    position: absolute;
    left: 20px;
    top: -24px;
    bottom: 0;
    width: 1px;
    background-color: #324d67;
    z-index: 0;
  }
  .agent-item:last-child .tree-line-vertical {
    bottom: 50%;
  }
  .agent-item .tree-line-horizontal {
    position: absolute;
    left: 20px;
    top: 50%;
    width: 24px;
    height: 1px;
    background-color: #324d67;
    z-index: 0;
  }
  .custom-scrollbar::-webkit-scrollbar {
    width: 6px;
  }
  .custom-scrollbar::-webkit-scrollbar-track {
    background: transparent;
  }
  .custom-scrollbar::-webkit-scrollbar-thumb {
    background: #324d67;
    border-radius: 10px;
  }
`

export default function BackupManagement() {
  const location = useLocation()
  const searchParams = new URLSearchParams(location.search)
  const tabFromUrl = searchParams.get('tab') as 'dashboard' | 'jobs' | 'clients' | 'storage' | 'filesets' | 'console' | null
  
  const [activeTab, setActiveTab] = useState<'dashboard' | 'jobs' | 'clients' | 'storage' | 'filesets' | 'console'>(
    tabFromUrl || 'dashboard'
  )
  const [searchQuery, setSearchQuery] = useState('')
  const queryClient = useQueryClient()
  
  // Sync activeTab with URL query parameter when URL changes (e.g., from navigation)
  useEffect(() => {
    const currentTab = new URLSearchParams(location.search).get('tab')
    // Handle legacy pools/volumes tabs by redirecting to storage
    if (currentTab === 'pools' || currentTab === 'volumes') {
      const newSearchParams = new URLSearchParams(location.search)
      newSearchParams.set('tab', 'storage')
      if (currentTab === 'volumes') {
        newSearchParams.set('view', 'volumes')
      } else if (currentTab === 'pools') {
        newSearchParams.set('view', 'pools')
      }
      const newUrl = `${location.pathname}?${newSearchParams.toString()}`
      window.history.replaceState({}, '', newUrl)
      setActiveTab('storage')
      return
    }
    const newTab = (currentTab as typeof activeTab) || 'dashboard'
    if (newTab !== activeTab && (newTab === 'dashboard' || newTab === 'jobs' || newTab === 'clients' || newTab === 'storage' || newTab === 'filesets' || newTab === 'console')) {
      setActiveTab(newTab)
    }
  }, [location.search, location.pathname])

  // Helper function to change tab and update URL
  const changeTab = (tab: typeof activeTab) => {
    setActiveTab(tab)
    const newSearchParams = new URLSearchParams(location.search)
    if (tab === 'dashboard') {
      newSearchParams.delete('tab')
    } else {
      newSearchParams.set('tab', tab)
    }
    const newUrl = `${location.pathname}${newSearchParams.toString() ? '?' + newSearchParams.toString() : ''}`
    window.history.replaceState({}, '', newUrl)
  }
  
  // Fetch dashboard stats
  const { data: dashboardStats } = useQuery({
    queryKey: ['dashboard-stats'],
    queryFn: () => backupAPI.getDashboardStats(),
    enabled: activeTab === 'dashboard',
    refetchInterval: 30000, // Refresh every 30 seconds
  })

  // Fetch recent jobs for dashboard
  const { data: dashboardJobsData } = useQuery({
    queryKey: ['dashboard-jobs'],
    queryFn: () => backupAPI.listJobs({ limit: 10 }),
    enabled: activeTab === 'dashboard',
  })

  // Fetch running jobs
  const { data: runningJobsData } = useQuery({
    queryKey: ['running-jobs'],
    queryFn: () => backupAPI.listJobs({ status: 'Running', limit: 10 }),
    enabled: activeTab === 'dashboard',
    refetchInterval: 5000, // Refresh every 5 seconds for running jobs
  })
  
  const recentJobs = dashboardJobsData?.jobs || []
  const runningJobs = runningJobsData?.jobs || []

  // Helper functions for formatting
  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 `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`
  }

  const formatDate = (dateStr?: string): string => {
    if (!dateStr) return '-'
    try {
      const date = new Date(dateStr)
      const now = new Date()
      const diffMs = now.getTime() - date.getTime()
      const diffMins = Math.floor(diffMs / 60000)
      const diffHours = Math.floor(diffMs / 3600000)
      const diffDays = Math.floor(diffMs / 86400000)

      if (diffMins < 1) return 'Just now'
      if (diffMins < 60) return `${diffMins}m ago`
      if (diffHours < 24) return `${diffHours}h ago`
      if (diffDays < 7) return `${diffDays}d ago`
      return date.toLocaleDateString()
    } catch {
      return '-'
    }
  }

  const formatDuration = (seconds?: number): string => {
    if (!seconds) return '-'
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const secs = seconds % 60
    if (hours > 0) {
      return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    }
    return `${minutes}:${secs.toString().padStart(2, '0')}`
  }

  // getStatusBadge function moved to JobsManagementTab component


  return (
    <div className="flex-1 flex flex-col overflow-hidden bg-slate-50 dark:bg-[#101922]">
      {/* Main Content Area */}
      <main className="flex-1 flex flex-col overflow-hidden">
        {/* Top Navbar */}
        <header className="h-16 flex items-center justify-between px-8 bg-white dark:bg-[#111a22] border-b border-slate-200 dark:border-[#233648] z-10">
          <div className="flex items-center gap-6 flex-1">
            <div className="flex items-center gap-3">
              <div className="size-10 bg-primary rounded-lg flex items-center justify-center text-white">
                <span className="material-symbols-outlined">backup</span>
              </div>
              <div>
                <h1 className="text-lg font-bold leading-tight">Backup Management</h1>
                <p className="text-xs text-slate-500 dark:text-[#92adc9]">Backup Appliance</p>
              </div>
            </div>
            <div className="relative w-full max-w-md">
              <span className="material-symbols-outlined absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-[20px]">search</span>
              <input
                className="w-full bg-slate-100 dark:bg-[#233648] border-none rounded-lg pl-10 pr-4 py-2 text-sm focus:ring-2 focus:ring-primary/50 transition-all outline-none"
                placeholder="Search clients, jobs, or logs..."
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
            </div>
          </div>
          <div className="flex items-center gap-4">
            <div className="flex items-center gap-2 px-3 py-1.5 bg-green-500/10 text-green-500 rounded-full border border-green-500/20">
              <span className="w-2 h-2 rounded-full bg-green-500 animate-pulse"></span>
              <span className="text-xs font-bold uppercase tracking-tighter">
                {dashboardStats?.director_status === 'Active' ? 'SD Connected' : 'SD Disconnected'}
              </span>
            </div>
            <button className="p-2 text-slate-500 hover:bg-slate-100 dark:hover:bg-[#233648] rounded-lg relative">
              <span className="material-symbols-outlined">notifications</span>
              <span className="absolute top-2 right-2 w-2 h-2 bg-primary rounded-full border-2 border-white dark:border-[#111a22]"></span>
            </button>
            <button
              onClick={() => {
                queryClient.invalidateQueries({ queryKey: ['dashboard-stats'] })
                queryClient.invalidateQueries({ queryKey: ['dashboard-jobs'] })
                queryClient.invalidateQueries({ queryKey: ['running-jobs'] })
              }}
              className="p-2 text-slate-500 hover:bg-slate-100 dark:hover:bg-[#233648] rounded-lg"
            >
              <span className="material-symbols-outlined">refresh</span>
            </button>
          </div>
        </header>

        {/* Dashboard Scrollable Body */}
        <div className="flex-1 overflow-y-auto p-8 space-y-8 custom-scrollbar bg-slate-50 dark:bg-[#101922]">

          {/* Conditional Content Based on Active Tab */}
          {activeTab === 'dashboard' && (
            <>
              {/* Summary Stats Section */}
              <section>
                <div className="flex items-center justify-between mb-4">
                  <h3 className="text-sm font-bold uppercase tracking-widest text-slate-500 dark:text-[#92adc9]">Job Statistics (Last 24h)</h3>
                  <button 
                    onClick={() => changeTab('jobs')}
                    className="text-xs font-medium text-primary cursor-pointer hover:underline"
                  >
                    View detailed report
                  </button>
                </div>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                  <div className="bg-white dark:bg-[#111a22] border border-slate-200 dark:border-[#324d67] p-6 rounded-xl flex flex-col gap-1 hover:border-primary/50 transition-colors cursor-default">
                    <p className="text-slate-500 dark:text-[#92adc9] text-sm font-medium">Successful Backups</p>
                    <div className="flex items-end justify-between">
                      <span className="text-3xl font-bold">
                        {recentJobs.filter(j => j.status === 'Completed').length}
                      </span>
                      <span className="text-green-500 text-sm font-bold flex items-center gap-1">
                        <span className="material-symbols-outlined text-[18px]">trending_up</span>
                        +12%
                      </span>
                    </div>
                  </div>
                  <div className="bg-white dark:bg-[#111a22] border border-slate-200 dark:border-[#324d67] p-6 rounded-xl flex flex-col gap-1 hover:border-primary/50 transition-colors cursor-default">
                    <p className="text-slate-500 dark:text-[#92adc9] text-sm font-medium">Failed Jobs</p>
                    <div className="flex items-end justify-between">
                      <span className="text-3xl font-bold">
                        {recentJobs.filter(j => j.status === 'Failed').length}
                      </span>
                      <span className="text-red-500 text-sm font-bold flex items-center gap-1">
                        <span className="material-symbols-outlined text-[18px]">trending_down</span>
                        -5%
                      </span>
                    </div>
                  </div>
                  <div className="bg-white dark:bg-[#111a22] border border-slate-200 dark:border-[#324d67] p-6 rounded-xl flex flex-col gap-1 hover:border-primary/50 transition-colors cursor-default">
                    <p className="text-slate-500 dark:text-[#92adc9] text-sm font-medium">Currently Running</p>
                    <div className="flex items-end justify-between">
                      <span className="text-3xl font-bold">{runningJobs.length}</span>
                      <span className="text-primary text-sm font-bold flex items-center gap-1">
                        <span className="material-symbols-outlined text-[18px]">sync</span>
                        Active
                      </span>
                    </div>
                  </div>
                  <div className="bg-white dark:bg-[#111a22] border border-slate-200 dark:border-[#324d67] p-6 rounded-xl flex flex-col gap-1 hover:border-primary/50 transition-colors cursor-default">
                    <p className="text-slate-500 dark:text-[#92adc9] text-sm font-medium">Waiting / Queued</p>
                    <div className="flex items-end justify-between">
                      <span className="text-3xl font-bold">
                        {recentJobs.filter(j => j.status === 'Waiting').length}
                      </span>
                      <span className="text-slate-400 text-sm font-bold">No change</span>
                    </div>
                  </div>
                </div>
              </section>

              {/* Storage and Capacity Row */}
              <section className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div className="bg-white dark:bg-[#111a22] border border-slate-200 dark:border-[#233648] rounded-xl p-6">
                  <div className="flex items-center justify-between mb-6">
                    <h3 className="text-base font-bold">Storage Pool Utilization</h3>
                    <span className="material-symbols-outlined text-slate-400">info</span>
                  </div>
                  <div className="space-y-6">
                    <div>
                      <div className="flex justify-between text-sm mb-2">
                        <span className="text-slate-500 dark:text-[#92adc9]">
                          {dashboardStats?.default_pool?.name || 'Default Pool'}
                        </span>
                        <span className="font-bold">
                          {dashboardStats?.default_pool 
                            ? `${formatBytes(dashboardStats.default_pool.used_bytes)} / ${formatBytes(dashboardStats.default_pool.total_bytes)}`
                            : 'N/A'}
                        </span>
                      </div>
                      <div className="w-full bg-slate-100 dark:bg-[#233648] h-3 rounded-full overflow-hidden">
                        <div 
                          className="bg-primary h-full rounded-full" 
                          style={{ width: `${dashboardStats?.default_pool ? Math.min(dashboardStats.default_pool.usage_percent, 100) : 0}%` }}
                        ></div>
                      </div>
                    </div>
                    <div>
                      <div className="flex justify-between text-sm mb-2">
                        <span className="text-slate-500 dark:text-[#92adc9]">Offsite Cloud Sync</span>
                        <span className="font-bold">1.8 TB / 5.0 TB</span>
                      </div>
                      <div className="w-full bg-slate-100 dark:bg-[#233648] h-3 rounded-full overflow-hidden">
                        <div className="bg-green-500 h-full rounded-full" style={{ width: '36%' }}></div>
                      </div>
                    </div>
                  </div>
                </div>
                <div className="bg-white dark:bg-[#111a22] border border-slate-200 dark:border-[#233648] rounded-xl p-6">
                  <div className="flex items-center justify-between mb-6">
                    <h3 className="text-base font-bold">Resource Summary</h3>
                    <button className="text-primary text-sm font-semibold">View Hardware</button>
                  </div>
                  <div className="grid grid-cols-2 gap-4">
                    <div className="bg-slate-50 dark:bg-[#16232e] p-4 rounded-lg">
                      <p className="text-xs text-slate-500 dark:text-[#92adc9] uppercase font-bold mb-1">Active Volumes</p>
                      <p className="text-xl font-bold">34</p>
                    </div>
                    <div className="bg-slate-50 dark:bg-[#16232e] p-4 rounded-lg">
                      <p className="text-xs text-slate-500 dark:text-[#92adc9] uppercase font-bold mb-1">Total Clients</p>
                      <p className="text-xl font-bold">{dashboardStats?.active_jobs_count || 0}</p>
                    </div>
                    <div className="bg-slate-50 dark:bg-[#16232e] p-4 rounded-lg">
                      <p className="text-xs text-slate-500 dark:text-[#92adc9] uppercase font-bold mb-1">Last Full Backup</p>
                      <p className="text-xl font-bold">
                        {dashboardStats?.last_job ? formatDate(dashboardStats.last_job.ended_at || dashboardStats.last_job.started_at) : 'N/A'}
                      </p>
                    </div>
                    <div className="bg-slate-50 dark:bg-[#16232e] p-4 rounded-lg">
                      <p className="text-xs text-slate-500 dark:text-[#92adc9] uppercase font-bold mb-1">Catalog Size</p>
                      <p className="text-xl font-bold">12.4 GB</p>
                    </div>
                  </div>
                </div>
              </section>

              {/* Running Jobs Table */}
              {runningJobs.length > 0 && (
                <section className="bg-white dark:bg-[#111a22] border border-slate-200 dark:border-[#233648] rounded-xl overflow-hidden">
                  <div className="px-6 py-4 border-b border-slate-200 dark:border-[#233648] flex items-center justify-between">
                    <h3 className="text-base font-bold">Running Jobs</h3>
                    <button className="bg-primary text-white text-xs font-bold px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors">
                      Abort All
                    </button>
                  </div>
                  <div className="overflow-x-auto">
                    <table className="w-full text-left border-collapse">
                      <thead>
                        <tr className="bg-slate-50 dark:bg-[#16232e] text-[11px] uppercase tracking-wider text-slate-500 dark:text-[#92adc9] font-bold">
                          <th className="px-6 py-3">Job ID</th>
                          <th className="px-6 py-3">Client Name</th>
                          <th className="px-6 py-3">Level</th>
                          <th className="px-6 py-3">Progress</th>
                          <th className="px-6 py-3">Bytes Processed</th>
                          <th className="px-6 py-3">Actions</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-slate-100 dark:divide-[#233648]">
                        {runningJobs.map((job) => {
                          const progress = job.duration_seconds ? Math.min((job.duration_seconds / 3600) * 100, 100) : 45
                          return (
                            <tr key={job.id} className="hover:bg-slate-50 dark:hover:bg-[#16232e] transition-colors">
                              <td className="px-6 py-4 text-sm font-mono">{job.job_id}</td>
                              <td className="px-6 py-4 text-sm font-bold">{job.client_name}</td>
                              <td className="px-6 py-4 text-sm">
                                <span className={`px-2 py-0.5 rounded text-[10px] font-bold uppercase border ${
                                  job.job_level === 'Full' 
                                    ? 'bg-purple-500/10 text-purple-500 border-purple-500/20'
                                    : 'bg-blue-500/10 text-blue-500 border-blue-500/20'
                                }`}>
                                  {job.job_level}
                                </span>
                              </td>
                              <td className="px-6 py-4">
                                <div className="flex items-center gap-3">
                                  <div className="flex-1 bg-slate-200 dark:bg-[#233648] h-1.5 rounded-full overflow-hidden min-w-[100px]">
                                    <div className="bg-primary h-full" style={{ width: `${progress}%` }}></div>
                                  </div>
                                  <span className="text-xs font-bold">{Math.round(progress)}%</span>
                                </div>
                              </td>
                              <td className="px-6 py-4 text-sm">{formatBytes(job.bytes_written)}</td>
                              <td className="px-6 py-4">
                                <button className="text-slate-400 hover:text-red-500 transition-colors">
                                  <span className="material-symbols-outlined text-[20px]">cancel</span>
                                </button>
                              </td>
                            </tr>
                          )
                        })}
                      </tbody>
                    </table>
                  </div>
                </section>
              )}

              {/* History and Logs Section */}
              <section className="grid grid-cols-1 xl:grid-cols-3 gap-6">
                <div className="xl:col-span-2 bg-white dark:bg-[#111a22] border border-slate-200 dark:border-[#233648] rounded-xl overflow-hidden">
                  <div className="px-6 py-4 border-b border-slate-200 dark:border-[#233648] flex items-center justify-between">
                    <h3 className="text-base font-bold">Recent Job History</h3>
                    <button 
                      onClick={() => changeTab('jobs')}
                      className="text-primary text-xs font-bold hover:underline"
                    >
                      View All History
                    </button>
                  </div>
                  <div className="divide-y divide-slate-100 dark:divide-[#233648]">
                    {recentJobs.slice(0, 5).map((job) => (
                      <div key={job.id} className="px-6 py-3 flex items-center justify-between hover:bg-slate-50 dark:hover:bg-[#16232e] transition-colors">
                        <div className="flex items-center gap-4">
                          {job.status === 'Completed' ? (
                            <span className="material-symbols-outlined text-green-500">check_circle</span>
                          ) : job.status === 'Failed' ? (
                            <span className="material-symbols-outlined text-red-500">error</span>
                          ) : (
                            <span className="material-symbols-outlined text-primary">sync</span>
                          )}
                          <div>
                            <p className="text-sm font-bold">{job.job_name} - {job.client_name}</p>
                            <p className="text-[10px] text-slate-500">
                              {job.status === 'Failed' 
                                ? `Error: ${job.error_message || 'Unknown error'}`
                                : `Duration: ${formatDuration(job.duration_seconds)} • Size: ${formatBytes(job.bytes_written)}`
                              }
                            </p>
                          </div>
                        </div>
                        <span className="text-xs font-medium text-slate-400">
                          {job.ended_at ? new Date(job.ended_at).toLocaleTimeString() : new Date(job.started_at || '').toLocaleTimeString()}
                        </span>
                      </div>
                    ))}
                    {recentJobs.length === 0 && (
                      <div className="px-6 py-8 text-center text-slate-500 dark:text-[#92adc9]">
                        No recent jobs found
                      </div>
                    )}
                  </div>
                </div>
                {/* Live Log View */}
                <div className="bg-black/90 dark:bg-[#080c11] border border-slate-200 dark:border-[#233648] rounded-xl flex flex-col h-[300px] xl:h-auto">
                  <div className="px-4 py-2 border-b border-white/10 flex items-center justify-between bg-white/5">
                    <h3 className="text-xs font-bold text-slate-300 uppercase tracking-widest flex items-center gap-2">
                      <span className="w-1.5 h-1.5 rounded-full bg-primary animate-pulse"></span>
                      Live Console Log
                    </h3>
                    <button className="text-white/40 hover:text-white">
                      <span className="material-symbols-outlined text-[16px]">open_in_new</span>
                    </button>
                  </div>
                  <div className="p-4 flex-1 overflow-y-auto custom-scrollbar font-mono text-[11px] space-y-1">
                    <p className="text-blue-400">15:40:12 [Director] Starting JobId {runningJobs[0]?.job_id || '10928'}</p>
                    <p className="text-slate-400">15:40:15 [SD] Ready to receive data on port 9103</p>
                    <p className="text-slate-400">15:40:18 [FD] Sending attribute data for /etc/passwd</p>
                    {dashboardStats?.last_job && (
                      <p className="text-green-400">15:42:01 [Director] JobId {dashboardStats.last_job.job_id} finished successfully</p>
                    )}
                    <p className="text-slate-400">15:42:05 [Catalog] Pruning expired volumes for Pool "Default"</p>
                    <p className="text-slate-500">15:43:00 [System] Health check completed - All systems OK</p>
                    <p className="text-yellow-400">15:43:45 [SD] Warning: Volume VOL-0045 reached 90% capacity</p>
                    <p className="text-blue-400">15:45:10 [Director] Scheduling next job "NightlyAudit"</p>
                  </div>
                </div>
              </section>
            </>
          )}

          {activeTab === 'jobs' && (
            <JobsManagementTab />
          )}

          {activeTab === 'clients' && (
            <ClientsManagementTab onSwitchToConsole={() => changeTab('console')} />
          )}

          {activeTab === 'storage' && (
            <StorageManagementTab />
          )}

          {activeTab === 'console' && (
            <BackupConsoleTab />
          )}
        </div>
      </main>
    </div>
  )
}

// Jobs Management Tab Component
function JobsManagementTab() {
  const queryClient = useQueryClient()
  const [statusFilter, setStatusFilter] = useState<string>('')
  const [expandedJobId, setExpandedJobId] = useState<string | null>(null)
  const [showCreateForm, setShowCreateForm] = useState(false)
  const [currentMonth, setCurrentMonth] = useState(new Date())

  const { data, isLoading, error } = useQuery({
    queryKey: ['backup-jobs', statusFilter],
    queryFn: () => backupAPI.listJobs({
      status: statusFilter || undefined,
      limit: 50,
    }),
  })

  const jobs = data?.jobs || []
  const runningJobs = jobs.filter(j => j.status === 'Running')
  const completedJobs = jobs.filter(j => j.status === 'Completed')
  const failedJobs = jobs.filter(j => j.status === 'Failed')

  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 `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`
  }

  const formatTimeAgo = (dateString?: string): string => {
    if (!dateString) return '-'
    try {
      const date = new Date(dateString)
      const now = new Date()
      const diffMs = now.getTime() - date.getTime()
      const diffMins = Math.floor(diffMs / 60000)
      const diffHours = Math.floor(diffMins / 60)
      const diffDays = Math.floor(diffHours / 24)
      
      if (diffMins < 1) return 'Just now'
      if (diffMins < 60) return `${diffMins}m ago`
      if (diffHours < 24) return `${diffHours}h ago`
      if (diffDays < 7) return `${diffDays}d ago`
      return date.toLocaleDateString()
    } catch {
      return '-'
    }
  }

  const formatNextRun = (job: any): string => {
    // This would need to be calculated based on schedule, for now return placeholder
    if (job.status === 'Running') return 'N/A'
    return 'Today 22:00' // Placeholder
  }

  const getStatusDisplay = (status: string) => {
    switch (status) {
      case 'Completed':
        return { dot: 'bg-success', text: 'text-success', label: 'Success' }
      case 'Running':
        return { dot: 'bg-primary', text: 'text-primary', label: 'Running' }
      case 'Failed':
        return { dot: 'bg-danger', text: 'text-danger', label: 'Failed' }
      case 'Canceled':
        return { dot: 'bg-warning', text: 'text-warning', label: 'Warning' }
      default:
        return { dot: 'bg-success', text: 'text-success', label: 'Success' }
    }
  }

  const getLevelBadge = (level: string) => {
    const levelMap: Record<string, { bg: string; text: string; border: string }> = {
      'Full': { bg: 'bg-white/10', text: 'text-white', border: 'border-white/20' },
      'Incremental': { bg: 'bg-blue-500/10', text: 'text-primary', border: 'border-primary/20' },
      'Differential': { bg: 'bg-amber-500/10', text: 'text-warning', border: 'border-warning/20' },
    }
    const config = levelMap[level] || levelMap['Incremental']
    return (
      <span className={`${config.bg} ${config.text} px-2 py-0.5 rounded text-[10px] font-black border ${config.border} uppercase`}>
        {level === 'Incremental' ? 'Inc' : level === 'Differential' ? 'Diff' : level}
      </span>
    )
  }

  // Calendar helpers
  const getDaysInMonth = (date: Date) => {
    const year = date.getFullYear()
    const month = date.getMonth()
    const firstDay = new Date(year, month, 1)
    const lastDay = new Date(year, month + 1, 0)
    const daysInMonth = lastDay.getDate()
    const startingDayOfWeek = firstDay.getDay()
    
    const days: (number | null)[] = []
    // Add empty cells for days before month starts
    for (let i = 0; i < startingDayOfWeek; i++) {
      days.push(null)
    }
    // Add days of the month
    for (let i = 1; i <= daysInMonth; i++) {
      days.push(i)
    }
    return days
  }

  const calendarDays = getDaysInMonth(currentMonth)
  const today = new Date().getDate()

  // Calculate health score (placeholder logic)
  const healthScore = jobs.length > 0 
    ? ((completedJobs.length / jobs.length) * 100).toFixed(1)
    : '100.0'

  return (
    <div className="flex-1 max-w-[1440px] mx-auto w-full px-6 py-6">
      {/* Toolbar & Page Heading */}
      <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-6 mb-8">
        <div>
          <h1 className="text-4xl font-extrabold tracking-tighter mb-2 dark:text-white">Jobs & Schedules</h1>
          <p className="text-slate-400 max-w-xl dark:text-slate-400">
            Configure, monitor, and manage Bacula backup policies and automated job schedules from a unified cockpit.
          </p>
        </div>
        <div className="flex items-center gap-3">
          <button className="bg-[#22252a] dark:bg-[#22252a] hover:bg-[#22252a]/80 px-4 py-2.5 rounded-lg flex items-center gap-2 font-bold text-sm transition-all border border-white/5 text-white">
            <span className="material-symbols-outlined text-lg">settings</span>
            <span>Config</span>
          </button>
          <button className="bg-[#22252a] dark:bg-[#22252a] hover:bg-[#22252a]/80 px-4 py-2.5 rounded-lg flex items-center gap-2 font-bold text-sm transition-all border border-white/5 text-white">
            <span className="material-symbols-outlined text-lg text-primary">history</span>
            <span>Restore</span>
          </button>
          <button 
            onClick={() => setShowCreateForm(true)}
            className="bg-primary hover:bg-primary/90 px-5 py-2.5 rounded-lg flex items-center gap-2 font-bold text-sm text-white shadow-lg shadow-primary/20 transition-all"
          >
            <span className="material-symbols-outlined text-lg">add_circle</span>
            <span>Add New Job</span>
          </button>
        </div>
      </div>

      {/* Filters Section */}
      <div className="flex flex-wrap gap-2 mb-6">
        <button 
          onClick={() => setStatusFilter('')}
          className={`text-xs font-bold px-4 py-1.5 rounded-full transition-colors ${
            !statusFilter 
              ? 'bg-primary text-white' 
              : 'bg-[#22252a] dark:bg-[#22252a] text-slate-400 hover:text-white'
          }`}
        >
          All Jobs
        </button>
        <button 
          onClick={() => setStatusFilter('Running')}
          className={`text-xs font-bold px-4 py-1.5 rounded-full transition-colors ${
            statusFilter === 'Running'
              ? 'bg-primary text-white'
              : 'bg-[#22252a] dark:bg-[#22252a] text-slate-400 hover:text-white'
          }`}
        >
          Running ({runningJobs.length})
        </button>
        <button 
          onClick={() => setStatusFilter('Completed')}
          className={`text-xs font-bold px-4 py-1.5 rounded-full transition-colors ${
            statusFilter === 'Completed'
              ? 'bg-primary text-white'
              : 'bg-[#22252a] dark:bg-[#22252a] text-slate-400 hover:text-white'
          }`}
        >
          Completed
        </button>
        <button 
          onClick={() => setStatusFilter('Failed')}
          className={`text-xs font-bold px-4 py-1.5 rounded-full transition-colors ${
            statusFilter === 'Failed'
              ? 'bg-primary text-white'
              : 'bg-[#22252a] dark:bg-[#22252a] text-slate-400 hover:text-white'
          }`}
        >
          Failed
        </button>
        <button 
          onClick={() => setStatusFilter('Waiting')}
          className={`text-xs font-bold px-4 py-1.5 rounded-full transition-colors ${
            statusFilter === 'Waiting'
              ? 'bg-primary text-white'
              : 'bg-[#22252a] dark:bg-[#22252a] text-slate-400 hover:text-white'
          }`}
        >
          Idle
        </button>
        <div className="ml-auto flex gap-2">
          <button className="p-1.5 text-slate-400 hover:text-white">
            <span className="material-symbols-outlined">filter_list</span>
          </button>
          <button className="p-1.5 text-slate-400 hover:text-white">
            <span className="material-symbols-outlined">grid_view</span>
          </button>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
        {/* Left: Job Management Table */}
        <div className="lg:col-span-8 space-y-4">
          <div className="bg-[#1a1d21] dark:bg-[#1a1d21] border border-white/10 rounded-xl overflow-hidden shadow-sm">
            {isLoading ? (
              <div className="p-8 text-center text-slate-400">Loading jobs...</div>
            ) : error ? (
              <div className="p-8 text-center text-red-400">Failed to load jobs</div>
            ) : jobs.length === 0 ? (
              <div className="p-12 text-center text-slate-400">No jobs found</div>
            ) : (
              <>
                <table className="w-full text-left border-collapse">
                  <thead>
                    <tr className="bg-[#22252a]/50 text-slate-400 text-[11px] uppercase tracking-widest border-b border-white/10">
                      <th className="px-6 py-4 font-bold">Status</th>
                      <th className="px-4 py-4 font-bold">Job Name</th>
                      <th className="px-4 py-4 font-bold">Level</th>
                      <th className="px-4 py-4 font-bold">Last Run</th>
                      <th className="px-4 py-4 font-bold">Next Run</th>
                      <th className="px-6 py-4 font-bold text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-white/5">
                    {jobs.slice(0, 10).map((job) => {
                      const statusDisplay = getStatusDisplay(job.status)
                      const isExpanded = expandedJobId === job.id
                      return (
                        <>
                          <tr 
                            key={job.id} 
                            className={`transition-colors group ${
                              job.status === 'Running' 
                                ? 'bg-primary/[0.03] hover:bg-primary/[0.05]' 
                                : 'hover:bg-white/[0.02]'
                            }`}
                            onClick={() => setExpandedJobId(isExpanded ? null : job.id)}
                          >
                            <td className="px-6 py-5">
                              <div className="flex items-center gap-2">
                                <div className={`w-2 h-2 rounded-full ${statusDisplay.dot} status-dot ${job.status === 'Running' ? 'animate-pulse' : ''}`}></div>
                                <span className={`text-xs font-bold ${statusDisplay.text} uppercase`}>
                                  {statusDisplay.label}
                                </span>
                              </div>
                            </td>
                            <td className="px-4 py-5">
                              <div className="flex flex-col">
                                <span className="font-bold text-sm tracking-tight text-white">{job.job_name}</span>
                                <span className="text-[10px] text-slate-500 uppercase tracking-tighter">
                                  SD: {job.storage_name || 'N/A'} | Pool: {job.pool_name || 'N/A'}
                                </span>
                              </div>
                            </td>
                            <td className="px-4 py-5">
                              {getLevelBadge(job.job_level)}
                            </td>
                            <td className={`px-4 py-5 text-sm ${job.status === 'Running' ? 'text-primary font-bold' : 'text-slate-300'}`}>
                              {job.status === 'Running' ? 'Active' : formatTimeAgo(job.ended_at || job.started_at)}
                            </td>
                            <td className="px-4 py-5 text-sm text-slate-300 font-medium">
                              {formatNextRun(job)}
                            </td>
                            <td className="px-6 py-5 text-right">
                              {job.status === 'Running' ? (
                                <button className="bg-danger/20 hover:bg-danger text-danger hover:text-white px-3 py-1 rounded-md text-[11px] font-bold transition-all uppercase">
                                  Stop
                                </button>
                              ) : (
                                <button className="bg-primary/20 hover:bg-primary text-primary hover:text-white px-3 py-1 rounded-md text-[11px] font-bold transition-all">
                                  RUN
                                </button>
                              )}
                            </td>
                          </tr>
                          {isExpanded && (
                            <tr>
                              <td colSpan={6} className="px-6 py-5 bg-[#22252a]/20 border-t border-white/5">
                                <div className="flex items-start gap-8">
                                  <div className="space-y-4 flex-1">
                                    <h4 className="text-xs font-bold uppercase tracking-widest text-primary">Live Stats</h4>
                                    <div className="grid grid-cols-3 gap-4">
                                      <div className="bg-[#121416]/50 p-3 rounded border border-white/5">
                                        <p className="text-[10px] text-slate-500 font-bold uppercase">Files Tracked</p>
                                        <p className="text-xl font-bold font-display text-white">{job.files_written.toLocaleString()}</p>
                                      </div>
                                      <div className="bg-[#121416]/50 p-3 rounded border border-white/5">
                                        <p className="text-[10px] text-slate-500 font-bold uppercase">Storage Used</p>
                                        <p className="text-xl font-bold font-display text-white">{formatBytes(job.bytes_written)}</p>
                                      </div>
                                      <div className="bg-[#121416]/50 p-3 rounded border border-white/5">
                                        <p className="text-[10px] text-slate-500 font-bold uppercase">Duration</p>
                                        <p className="text-xl font-bold font-display text-white">
                                          {job.duration_seconds ? `${Math.floor(job.duration_seconds / 60)}m` : '-'}
                                        </p>
                                      </div>
                                    </div>
                                  </div>
                                  <div className="w-64 space-y-3">
                                    <h4 className="text-xs font-bold uppercase tracking-widest text-slate-400">Job Details</h4>
                                    <ul className="text-xs space-y-2">
                                      <li className="flex justify-between border-b border-white/5 pb-1">
                                        <span className="text-slate-500">Client</span>
                                        <span className="font-bold text-white">{job.client_name}</span>
                                      </li>
                                      <li className="flex justify-between border-b border-white/5 pb-1">
                                        <span className="text-slate-500">Type</span>
                                        <span className="font-bold text-white">{job.job_type}</span>
                                      </li>
                                      <li className="flex justify-between border-b border-white/5 pb-1">
                                        <span className="text-slate-500">Job ID</span>
                                        <span className="font-bold text-white">{job.job_id}</span>
                                      </li>
                                    </ul>
                                  </div>
                                </div>
                              </td>
                            </tr>
                          )}
                        </>
                      )
                    })}
                  </tbody>
                </table>
              </>
            )}
          </div>
        </div>

        {/* Right: Schedule & Mini-Calendar */}
        <div className="lg:col-span-4 space-y-6">
          {/* Mini Calendar Card */}
          <div className="bg-[#1a1d21] dark:bg-[#1a1d21] border border-white/10 rounded-xl p-5 shadow-sm">
            <div className="flex items-center justify-between mb-6">
              <h3 className="font-bold text-sm tracking-tight flex items-center gap-2 text-white">
                <span className="material-symbols-outlined text-primary text-xl">calendar_month</span>
                Backup Window Schedule
              </h3>
              <div className="flex gap-1">
                <button 
                  onClick={() => setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() - 1, 1))}
                  className="p-1 hover:bg-white/10 rounded"
                >
                  <span className="material-symbols-outlined text-sm text-slate-400">chevron_left</span>
                </button>
                <button 
                  onClick={() => setCurrentMonth(new Date(currentMonth.getFullYear(), currentMonth.getMonth() + 1, 1))}
                  className="p-1 hover:bg-white/10 rounded"
                >
                  <span className="material-symbols-outlined text-sm text-slate-400">chevron_right</span>
                </button>
              </div>
            </div>
            <div className="grid grid-cols-7 gap-1 text-center mb-4">
              {['S', 'M', 'T', 'W', 'T', 'F', 'S'].map((day, idx) => (
                <div key={idx} className="text-[10px] font-bold text-slate-500 uppercase">{day}</div>
              ))}
              {calendarDays.map((day, idx) => {
                if (day === null) {
                  return <div key={idx} className="aspect-square flex items-center justify-center text-[11px] opacity-20"></div>
                }
                const isToday = day === today && currentMonth.getMonth() === new Date().getMonth()
                const hasJob = Math.random() > 0.7 // Placeholder logic
                return (
                  <div 
                    key={idx} 
                    className={`aspect-square flex items-center justify-center text-[11px] relative ${
                      isToday ? 'bg-primary text-white rounded font-bold' : 'text-white'
                    }`}
                  >
                    {day}
                    {hasJob && !isToday && (
                      <div className="absolute bottom-1 w-1 h-1 bg-primary rounded-full"></div>
                    )}
                  </div>
                )
              })}
            </div>
            <div className="mt-6 pt-6 border-t border-white/5 space-y-4">
              <h4 className="text-[10px] font-bold text-slate-500 uppercase tracking-widest">Upcoming Jobs</h4>
              <div className="flex items-center gap-4">
                <div className="bg-[#22252a] rounded px-2 py-1 text-center min-w-[48px]">
                  <p className="text-[10px] font-bold text-slate-500 uppercase">Today</p>
                  <p className="text-xs font-black text-white">22:00</p>
                </div>
                <div className="flex-1">
                  <p className="text-xs font-bold leading-none mb-1 tracking-tight text-white">Cloud_Incremental</p>
                  <p className="text-[10px] text-slate-500 uppercase">Priority: 10</p>
                </div>
              </div>
              <div className="flex items-center gap-4">
                <div className="bg-[#22252a] rounded px-2 py-1 text-center min-w-[48px]">
                  <p className="text-[10px] font-bold text-slate-500 uppercase">Today</p>
                  <p className="text-xs font-black text-white">23:30</p>
                </div>
                <div className="flex-1">
                  <p className="text-xs font-bold leading-none mb-1 tracking-tight text-white">VM_Snapshot_Cluster</p>
                  <p className="text-[10px] text-slate-500 uppercase">Priority: 15</p>
                </div>
              </div>
            </div>
          </div>

          {/* Info Box */}
          <div className="bg-primary/5 border border-[#1f5c9c]/30 rounded-xl p-5 relative overflow-hidden">
            <div className="absolute top-0 right-0 w-32 h-32 bg-primary/5 rounded-full -mr-16 -mt-16 blur-3xl"></div>
            <div className="relative z-10">
              <span className="material-symbols-outlined text-primary mb-3">verified</span>
              <h4 className="font-bold text-sm tracking-tight mb-2 text-white">Backup Health Score</h4>
              <div className="flex items-end gap-2 mb-4">
                <span className="text-3xl font-black text-primary leading-none">{healthScore}%</span>
                <span className="text-[10px] text-success font-bold pb-1">+0.4% this week</span>
              </div>
              <div className="w-full bg-white/5 rounded-full h-1.5 overflow-hidden">
                <div className="bg-primary h-full rounded-full" style={{ width: `${healthScore}%` }}></div>
              </div>
              <p className="text-[11px] text-slate-400 mt-4 leading-relaxed italic">
                The last {jobs.length} jobs completed. {failedJobs.length} job{failedJobs.length !== 1 ? 's' : ''} required manual intervention.
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Footer Status */}
      <footer className="mt-8 border-t border-white/5 bg-[#121416]/80 px-6 py-2 flex justify-between items-center text-[10px] text-slate-500 font-medium">
        <div className="flex gap-4">
          <span className="flex items-center gap-1">
            <span className="w-1.5 h-1.5 rounded-full bg-success"></span> Director: Online
          </span>
          <span className="flex items-center gap-1">
            <span className="w-1.5 h-1.5 rounded-full bg-success"></span> Storage: Online
          </span>
          <span className="flex items-center gap-1">
            <span className="w-1.5 h-1.5 rounded-full bg-success"></span> Database: 0.1ms
          </span>
        </div>
        <div className="flex gap-4 items-center">
          <span>v13.0.2 Bacula Community</span>
          <span>Up: 12d 4h 12m</span>
        </div>
      </footer>

      {/* Create Job Form Modal */}
      {showCreateForm && (
        <CreateJobForm
          onClose={() => setShowCreateForm(false)}
          onSuccess={async () => {
            setShowCreateForm(false)
            await queryClient.invalidateQueries({ queryKey: ['backup-jobs'] })
            await queryClient.refetchQueries({ queryKey: ['backup-jobs'] })
          }}
        />
      )}
    </div>
  )
}

// Create Job Form Component
interface CreateJobFormProps {
  onClose: () => void
  onSuccess: () => void
}

function CreateJobForm({ onClose, onSuccess }: CreateJobFormProps) {
  const [formData, setFormData] = useState({
    job_name: '',
    client_name: '',
    job_type: 'Backup',
    job_level: 'Full',
    storage_name: '',
    pool_name: '',
  })
  const [error, setError] = useState<string | null>(null)

  const createJobMutation = useMutation({
    mutationFn: backupAPI.createJob,
    onSuccess: () => {
      onSuccess()
    },
    onError: (err: any) => {
      setError(err.response?.data?.error || 'Failed to create job')
    },
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    setError(null)

    const payload: any = {
      job_name: formData.job_name,
      client_name: formData.client_name,
      job_type: formData.job_type,
      job_level: formData.job_level,
    }

    if (formData.storage_name) {
      payload.storage_name = formData.storage_name
    }
    if (formData.pool_name) {
      payload.pool_name = formData.pool_name
    }

    createJobMutation.mutate(payload)
  }

  return (
    <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
      <div className="bg-[#1c2936] border border-border-dark rounded-lg shadow-xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-border-dark">
          <h2 className="text-white text-xl font-bold">Create Backup Job</h2>
          <button
            onClick={onClose}
            className="text-text-secondary hover:text-white transition-colors"
          >
            <X size={20} />
          </button>
        </div>

        {/* Form */}
        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          {error && (
            <div className="p-3 bg-red-500/10 border border-red-500/20 rounded-lg text-red-400 text-sm">
              {error}
            </div>
          )}

          {/* Job Name */}
          <div>
            <label className="block text-white text-sm font-semibold mb-2">
              Job Name <span className="text-red-400">*</span>
            </label>
            <input
              type="text"
              required
              value={formData.job_name}
              onChange={(e) => setFormData({ ...formData, job_name: e.target.value })}
              className="w-full px-4 py-2 bg-[#111a22] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              placeholder="e.g., DailyBackup"
            />
          </div>

          {/* Client Name */}
          <div>
            <label className="block text-white text-sm font-semibold mb-2">
              Client Name <span className="text-red-400">*</span>
            </label>
            <input
              type="text"
              required
              value={formData.client_name}
              onChange={(e) => setFormData({ ...formData, client_name: e.target.value })}
              className="w-full px-4 py-2 bg-[#111a22] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              placeholder="e.g., filesrv-02"
            />
          </div>

          {/* Job Type & Level */}
          <div className="grid grid-cols-2 gap-4">
            <div>
              <label className="block text-white text-sm font-semibold mb-2">
                Job Type <span className="text-red-400">*</span>
              </label>
              <select
                required
                value={formData.job_type}
                onChange={(e) => setFormData({ ...formData, job_type: e.target.value })}
                className="w-full px-4 py-2 bg-[#111a22] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent appearance-none cursor-pointer"
                style={{
                  backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23ffffff' d='M6 9L1 4h10z'/%3E%3C/svg%3E")`,
                  backgroundRepeat: 'no-repeat',
                  backgroundPosition: 'right 0.75rem center',
                  paddingRight: '2.5rem',
                }}
              >
                <option value="Backup">Backup</option>
                <option value="Restore">Restore</option>
                <option value="Verify">Verify</option>
                <option value="Copy">Copy</option>
                <option value="Migrate">Migrate</option>
              </select>
            </div>

            <div>
              <label className="block text-white text-sm font-semibold mb-2">
                Job Level <span className="text-red-400">*</span>
              </label>
              <select
                required
                value={formData.job_level}
                onChange={(e) => setFormData({ ...formData, job_level: e.target.value })}
                className="w-full px-4 py-2 bg-[#111a22] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent appearance-none cursor-pointer"
                style={{
                  backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23ffffff' d='M6 9L1 4h10z'/%3E%3C/svg%3E")`,
                  backgroundRepeat: 'no-repeat',
                  backgroundPosition: 'right 0.75rem center',
                  paddingRight: '2.5rem',
                }}
              >
                <option value="Full">Full</option>
                <option value="Incremental">Incremental</option>
                <option value="Differential">Differential</option>
                <option value="Since">Since</option>
              </select>
            </div>
          </div>

          {/* Storage Name */}
          <div>
            <label className="block text-white text-sm font-semibold mb-2">
              Storage Name (Optional)
            </label>
            <input
              type="text"
              value={formData.storage_name}
              onChange={(e) => setFormData({ ...formData, storage_name: e.target.value })}
              className="w-full px-4 py-2 bg-[#111a22] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              placeholder="e.g., backup-srv-01"
            />
          </div>

          {/* Pool Name */}
          <div>
            <label className="block text-white text-sm font-semibold mb-2">
              Pool Name (Optional)
            </label>
            <input
              type="text"
              value={formData.pool_name}
              onChange={(e) => setFormData({ ...formData, pool_name: e.target.value })}
              className="w-full px-4 py-2 bg-[#111a22] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              placeholder="e.g., Default"
            />
          </div>

          {/* Actions */}
          <div className="flex items-center justify-end gap-3 pt-4 border-t border-border-dark">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 bg-[#111a22] border border-border-dark rounded-lg text-white text-sm font-semibold hover:bg-[#1c2936] transition-colors"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={createJobMutation.isPending}
              className="px-4 py-2 bg-primary text-white rounded-lg text-sm font-semibold hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {createJobMutation.isPending ? 'Creating...' : 'Create Job'}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}

// Backup Console Tab Component
function BackupConsoleTab() {
  const [commandHistory, setCommandHistory] = useState<Array<{ command: string; output: string; timestamp: Date }>>([])
  const [currentCommand, setCurrentCommand] = useState('')
  const [isExecuting, setIsExecuting] = useState(false)
  const terminalRef = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLInputElement>(null)

  // Auto-scroll to bottom when new output is added
  useEffect(() => {
    if (terminalRef.current) {
      terminalRef.current.scrollTop = terminalRef.current.scrollHeight
    }
  }, [commandHistory])

  // Focus input on mount
  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus()
    }
  }, [])

  const executeCommand = useMutation({
    mutationFn: (cmd: string) => backupAPI.executeBconsoleCommand(cmd),
    onSuccess: (data, command) => {
      setCommandHistory((prev) => [
        ...prev,
        {
          command,
          output: data.output,
          timestamp: new Date(),
        },
      ])
      setCurrentCommand('')
      setIsExecuting(false)
      // Focus input after command execution
      setTimeout(() => {
        if (inputRef.current) {
          inputRef.current.focus()
        }
      }, 100)
    },
    onError: (error: any) => {
      setCommandHistory((prev) => [
        ...prev,
        {
          command: currentCommand,
          output: error?.response?.data?.output || error?.response?.data?.details || error.message || 'Error executing command',
          timestamp: new Date(),
        },
      ])
      setCurrentCommand('')
      setIsExecuting(false)
      setTimeout(() => {
        if (inputRef.current) {
          inputRef.current.focus()
        }
      }, 100)
    },
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    const cmd = currentCommand.trim()
    if (!cmd || isExecuting) return

    setIsExecuting(true)
    executeCommand.mutate(cmd)
  }

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    // Handle Ctrl+L to clear (common terminal shortcut)
    if (e.ctrlKey && e.key === 'l') {
      e.preventDefault()
      setCommandHistory([])
    }
  }

  return (
    <div className="flex flex-col h-full bg-[#0a0f14] border border-border-dark rounded-xl overflow-hidden">
      {/* Terminal Header */}
      <div className="flex-none px-4 py-3 bg-[#161f29] border-b border-border-dark flex items-center justify-between">
        <div className="flex items-center gap-2">
          <span className="material-symbols-outlined text-base text-primary">terminal</span>
          <h3 className="text-white text-sm font-bold">Console View</h3>
        </div>
        <button
          onClick={() => setCommandHistory([])}
          className="text-xs text-text-secondary hover:text-white transition-colors"
        >
          Clear
        </button>
      </div>

      {/* Terminal Output */}
      <div
        ref={terminalRef}
        className="flex-1 overflow-y-auto p-4 bg-[#0a0f14] custom-scrollbar"
        style={{ minHeight: '400px' }}
      >
        {commandHistory.length === 0 ? (
          <div className="text-text-secondary">
            <div className="mb-2">Console View - Type commands below</div>
            <div className="text-xs opacity-70">
              <div>Common commands:</div>
              <div className="ml-4 mt-1">
                <div>• list jobs</div>
                <div>• list clients</div>
                <div>• list pools</div>
                <div>• status director</div>
                <div>• help</div>
              </div>
            </div>
          </div>
        ) : (
          commandHistory.map((item, idx) => (
            <div key={idx} className="mb-6">
              <div className="text-primary mb-2 font-mono text-sm">
                <span className="text-text-secondary">$</span> <span className="text-white">{item.command}</span>
              </div>
              <div 
                className="text-green-400 font-mono text-xs leading-relaxed whitespace-pre overflow-x-auto"
                style={{ 
                  fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',
                  lineHeight: '1.6',
                  tabSize: 2
                }}
              >
                {item.output}
              </div>
            </div>
          ))
        )}
        {isExecuting && (
          <div className="text-text-secondary">
            <span className="animate-pulse">Executing...</span>
          </div>
        )}
      </div>

      {/* Terminal Input */}
      <div className="flex-none border-t border-border-dark bg-[#161f29]">
        <form onSubmit={handleSubmit} className="flex items-center">
          <span className="px-4 text-primary font-mono text-sm">$</span>
          <input
            ref={inputRef}
            data-console-input
            type="text"
            value={currentCommand}
            onChange={(e) => setCurrentCommand(e.target.value)}
            onKeyDown={handleKeyDown}
            disabled={isExecuting}
            placeholder="Enter bconsole command..."
            className="flex-1 bg-transparent text-white font-mono text-sm py-3 focus:outline-none disabled:opacity-50"
          />
          <button
            type="submit"
            disabled={!currentCommand.trim() || isExecuting}
            className="px-4 py-3 text-primary hover:text-white disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            <span className="material-symbols-outlined text-base">send</span>
          </button>
        </form>
      </div>
    </div>
  )
}

// Clients Management Tab Component
function ClientsManagementTab({ onSwitchToConsole }: { onSwitchToConsole?: () => void }) {
  const [searchQuery, setSearchQuery] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>('all')
  const [categoryFilter, setCategoryFilter] = useState<string>('all')
  const [expandedRows, setExpandedRows] = useState<Set<number>>(new Set())
  const [selectAll, setSelectAll] = useState(false)
  const [selectedClients, setSelectedClients] = useState<Set<number>>(new Set())
  const [openMenuId, setOpenMenuId] = useState<number | null>(null)
  const [isStartingBackup, setIsStartingBackup] = useState<number | null>(null)
  const queryClient = useQueryClient()

  const { data, isLoading, error } = useQuery({
    queryKey: ['backup-clients', statusFilter, searchQuery, categoryFilter],
    queryFn: () => backupAPI.listClients({
      enabled: statusFilter === 'all' ? undefined : statusFilter === 'enabled',
      search: searchQuery || undefined,
      category: categoryFilter === 'all' ? undefined : categoryFilter as 'File' | 'Database' | 'Virtual',
    }),
  })

  // Mutation untuk start backup job
  const startBackupMutation = useMutation({
    mutationFn: async (clientName: string) => {
      // Gunakan bconsole command untuk run backup job
      // Format: run job=<job_name> client=<client_name>
      // Kita akan coba run job dengan nama yang sama dengan client name, atau "Backup-<client_name>"
      const jobName = `Backup-${clientName}`
      const command = `run job=${jobName} client=${clientName} yes`
      return backupAPI.executeBconsoleCommand(command)
    },
    onSuccess: () => {
      // Refresh clients list dan jobs list
      queryClient.invalidateQueries({ queryKey: ['backup-clients'] })
      queryClient.invalidateQueries({ queryKey: ['backup-jobs'] })
      setIsStartingBackup(null)
    },
    onError: (error: any) => {
      console.error('Failed to start backup:', error)
      setIsStartingBackup(null)
      alert(`Failed to start backup: ${error?.response?.data?.details || error.message || 'Unknown error'}`)
    },
  })

  const clients = data?.clients || []
  const total = data?.total || 0

  const formatDate = (dateStr?: string): string => {
    if (!dateStr) return '-'
    try {
      const date = new Date(dateStr)
      const now = new Date()
      const diffMs = now.getTime() - date.getTime()
      const diffMins = Math.floor(diffMs / 60000)
      const diffHours = Math.floor(diffMs / 3600000)
      const diffDays = Math.floor(diffMs / 86400000)

      if (diffMins < 1) return 'Just now'
      if (diffMins < 60) return `${diffMins}m ago`
      if (diffHours < 24) return `${diffHours}h ago`
      if (diffDays < 7) return `${diffDays}d ago`
      return date.toLocaleDateString()
    } catch {
      return '-'
    }
  }

  const getLastBackupStatus = (client: any): { status: 'success' | 'failed' | 'running' | 'warning', text: string, time: string } => {
    if (!client.last_backup_at) {
      return { status: 'warning', text: 'Never', time: 'No backup yet' }
    }
    
    const date = new Date(client.last_backup_at)
    const now = new Date()
    const diffMs = now.getTime() - date.getTime()
    const diffHours = Math.floor(diffMs / 3600000)
    const diffDays = Math.floor(diffMs / 86400000)

    // Mock logic - in real app, this would come from job status
    if (diffDays > 7) {
      return { status: 'failed', text: 'Failed', time: `${diffDays}d ago (Connection Timed Out)` }
    }
    if (diffHours > 24) {
      return { status: 'warning', text: 'Warning', time: `${diffHours}h ago (Some files skipped)` }
    }
    return { status: 'success', text: 'Success', time: formatDate(client.last_backup_at) + ' (Daily)' }
  }

  const toggleRow = (clientId: number) => {
    const newExpanded = new Set(expandedRows)
    if (newExpanded.has(clientId)) {
      newExpanded.delete(clientId)
    } else {
      newExpanded.add(clientId)
    }
    setExpandedRows(newExpanded)
  }

  const toggleSelectClient = (clientId: number) => {
    const newSelected = new Set(selectedClients)
    if (newSelected.has(clientId)) {
      newSelected.delete(clientId)
    } else {
      newSelected.add(clientId)
    }
    setSelectedClients(newSelected)
    setSelectAll(newSelected.size === clients.length)
  }

  const toggleSelectAll = () => {
    if (selectAll) {
      setSelectedClients(new Set())
    } else {
      setSelectedClients(new Set(clients.map(c => c.client_id)))
    }
    setSelectAll(!selectAll)
  }

  // Extract IP and port from uname (mock - in real app this would come from API)
  const getConnectionInfo = (client: any) => {
    // Try to extract IP from uname or use mock
    const uname = client.uname || ''
    const ipMatch = uname.match(/\d+\.\d+\.\d+\.\d+/)
    return {
      ip: ipMatch ? ipMatch[0] : '192.168.10.25',
      port: '9102'
    }
  }

  // Handler untuk start backup
  const handleStartBackup = (client: any) => {
    if (!client.name) {
      alert('Client name is required')
      return
    }
    setIsStartingBackup(client.client_id)
    startBackupMutation.mutate(client.name)
  }

  // Handler untuk edit config - redirect ke console dengan command
  const handleEditConfig = (client: any) => {
    const command = `show client=${client.name}`
    if (onSwitchToConsole) {
      onSwitchToConsole()
      // Set command di console setelah switch menggunakan custom event
      setTimeout(() => {
        const consoleInput = document.querySelector('input[data-console-input]') as HTMLInputElement
        if (consoleInput) {
          // Use Object.defineProperty to set value and trigger React onChange
          const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set
          if (nativeInputValueSetter) {
            nativeInputValueSetter.call(consoleInput, command)
            const event = new Event('input', { bubbles: true })
            consoleInput.dispatchEvent(event)
          } else {
            consoleInput.value = command
            consoleInput.dispatchEvent(new Event('input', { bubbles: true }))
          }
          consoleInput.focus()
        }
      }, 200)
    } else {
      // Fallback: buka console tab
      const consoleTab = document.querySelector('[data-tab="console"]') as HTMLElement
      if (consoleTab) {
        consoleTab.click()
        setTimeout(() => {
          const consoleInput = document.querySelector('input[data-console-input]') as HTMLInputElement
          if (consoleInput) {
            const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set
            if (nativeInputValueSetter) {
              nativeInputValueSetter.call(consoleInput, command)
              const event = new Event('input', { bubbles: true })
              consoleInput.dispatchEvent(event)
            } else {
              consoleInput.value = command
              consoleInput.dispatchEvent(new Event('input', { bubbles: true }))
            }
            consoleInput.focus()
          }
        }, 200)
      }
    }
  }

  // Handler untuk toggle dropdown menu
  const toggleMenu = (clientId: number) => {
    setOpenMenuId(openMenuId === clientId ? null : clientId)
  }

  // Close menu when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (openMenuId !== null) {
        const target = event.target as HTMLElement
        if (!target.closest('.dropdown-menu') && !target.closest('.menu-trigger')) {
          setOpenMenuId(null)
        }
      }
    }
    document.addEventListener('mousedown', handleClickOutside)
    return () => document.removeEventListener('mousedown', handleClickOutside)
  }, [openMenuId])

  return (
    <>
      <style>{clientManagementStyles}</style>
      <div className="flex flex-col gap-6 flex-1">
        {/* Header */}
      <header className="flex flex-wrap justify-between items-end gap-4 border-b border-border-dark pb-6">
        <div className="flex flex-col gap-2">
          <div className="flex items-center gap-3">
            <h1 className="text-white text-3xl md:text-4xl font-black leading-tight tracking-tight">Client Management</h1>
            <span className="flex h-6 px-2 items-center rounded-full bg-surface-highlight border border-border-dark text-xs font-bold text-primary">
              {total} Clients
            </span>
          </div>
          <p className="text-text-secondary text-base font-normal max-w-2xl">
            Monitor backup status, configure file daemons, and manage client connectivity.
          </p>
        </div>
        <div className="flex gap-3">
          <button 
            onClick={() => {
              if (onSwitchToConsole) {
                onSwitchToConsole()
              } else {
                const consoleTab = document.querySelector('[data-tab="console"]') as HTMLElement
                if (consoleTab) consoleTab.click()
              }
            }}
            className="flex items-center gap-2 cursor-pointer justify-center rounded-lg h-10 px-4 bg-surface-highlight border border-border-dark text-white text-sm font-bold hover:bg-[#2a3c50] transition-colors"
          >
            <span className="material-symbols-outlined text-base">terminal</span>
            <span>Console</span>
          </button>
          <button className="flex items-center gap-2 cursor-pointer justify-center rounded-lg h-10 px-4 bg-primary text-white text-sm font-bold shadow-lg shadow-primary/20 hover:bg-primary/90 transition-colors">
            <span className="material-symbols-outlined text-base">add</span>
            <span>Add New Client</span>
          </button>
        </div>
      </header>

      {/* Filters */}
      <div className="flex flex-wrap items-center justify-between gap-4 py-2">
        <div className="flex items-center gap-2 w-full md:w-auto flex-1">
          <div className="relative w-full max-w-sm">
            <span className="material-symbols-outlined absolute left-3 top-2.5 text-text-secondary text-[20px]">search</span>
            <input
              type="text"
              placeholder="Search clients by name, IP..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full bg-surface-highlight border border-border-dark text-white text-sm rounded-lg pl-10 pr-4 py-2 focus:ring-1 focus:ring-primary focus:border-primary outline-none placeholder-text-secondary/70 transition-all"
            />
          </div>
          <div className="hidden md:flex items-center gap-2">
            <div className="flex bg-surface-highlight border border-border-dark rounded-lg p-1 gap-1">
              <button
                onClick={() => setStatusFilter('all')}
                className={`px-3 py-1 rounded text-xs font-bold transition-colors ${
                  statusFilter === 'all' 
                    ? 'bg-surface-dark text-white shadow-sm border border-border-dark/50' 
                    : 'text-text-secondary hover:text-white hover:bg-surface-dark'
                }`}
              >
                All
              </button>
              <button
                onClick={() => setStatusFilter('online')}
                className={`px-3 py-1 rounded text-xs font-medium transition-colors ${
                  statusFilter === 'online' 
                    ? 'bg-surface-dark text-white shadow-sm border border-border-dark/50' 
                    : 'text-text-secondary hover:text-white hover:bg-surface-dark'
                }`}
              >
                Online
              </button>
              <button
                onClick={() => setStatusFilter('offline')}
                className={`px-3 py-1 rounded text-xs font-medium transition-colors ${
                  statusFilter === 'offline' 
                    ? 'bg-surface-dark text-white shadow-sm border border-border-dark/50' 
                    : 'text-text-secondary hover:text-white hover:bg-surface-dark'
                }`}
              >
                Offline
              </button>
              <button
                onClick={() => setStatusFilter('problems')}
                className={`px-3 py-1 rounded text-xs font-medium transition-colors ${
                  statusFilter === 'problems' 
                    ? 'bg-surface-dark text-white shadow-sm border border-border-dark/50' 
                    : 'text-text-secondary hover:text-white hover:bg-surface-dark'
                }`}
              >
                Problems
              </button>
            </div>
            <div className="flex bg-surface-highlight border border-border-dark rounded-lg p-1 gap-1">
              <button
                onClick={() => setCategoryFilter('all')}
                className={`px-3 py-1 rounded text-xs font-bold transition-colors ${
                  categoryFilter === 'all' 
                    ? 'bg-surface-dark text-white shadow-sm border border-border-dark/50' 
                    : 'text-text-secondary hover:text-white hover:bg-surface-dark'
                }`}
              >
                All Types
              </button>
              <button
                onClick={() => setCategoryFilter('File')}
                className={`px-3 py-1 rounded text-xs font-medium transition-colors ${
                  categoryFilter === 'File' 
                    ? 'bg-surface-dark text-white shadow-sm border border-border-dark/50' 
                    : 'text-text-secondary hover:text-white hover:bg-surface-dark'
                }`}
              >
                File
              </button>
              <button
                onClick={() => setCategoryFilter('Database')}
                className={`px-3 py-1 rounded text-xs font-medium transition-colors ${
                  categoryFilter === 'Database' 
                    ? 'bg-surface-dark text-white shadow-sm border border-border-dark/50' 
                    : 'text-text-secondary hover:text-white hover:bg-surface-dark'
                }`}
              >
                Database
              </button>
              <button
                onClick={() => setCategoryFilter('Virtual')}
                className={`px-3 py-1 rounded text-xs font-medium transition-colors ${
                  categoryFilter === 'Virtual' 
                    ? 'bg-surface-dark text-white shadow-sm border border-border-dark/50' 
                    : 'text-text-secondary hover:text-white hover:bg-surface-dark'
                }`}
              >
                Virtual
              </button>
            </div>
          </div>
        </div>
        <div className="flex gap-2">
          <button className="flex items-center gap-2 px-3 py-2 bg-surface-highlight border border-border-dark rounded-lg text-text-secondary hover:text-white transition-colors text-sm font-medium">
            <span className="material-symbols-outlined text-[18px]">sort</span>
            Sort: Status
          </button>
          <button className="md:hidden flex items-center justify-center p-2 bg-surface-highlight border border-border-dark rounded-lg text-text-secondary">
            <span className="material-symbols-outlined">filter_list</span>
          </button>
        </div>
      </div>

      {/* Clients Table */}
      <div className="rounded-lg border border-border-dark bg-surface-highlight overflow-hidden shadow-sm flex flex-col flex-1">
        {isLoading ? (
          <div className="p-8 text-center text-text-secondary">Loading clients...</div>
        ) : error ? (
          <div className="p-8 text-center text-red-400">Failed to load clients</div>
        ) : clients.length === 0 ? (
          <div className="p-12 text-center">
            <p className="text-text-secondary">No clients found</p>
          </div>
        ) : (
          <>
            <div className="overflow-x-auto">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="bg-surface-dark border-b border-border-dark text-text-secondary text-xs uppercase tracking-wider">
                    <th className="px-6 py-4 w-12">
                      <input 
                        type="checkbox" 
                        className="checkbox-custom"
                        checked={selectAll}
                        onChange={toggleSelectAll}
                      />
                    </th>
                    <th className="px-6 py-4 font-semibold w-8"></th>
                    <th className="px-6 py-4 font-semibold">Client Name</th>
                    <th className="px-6 py-4 font-semibold">Category</th>
                    <th className="px-6 py-4 font-semibold">Connection</th>
                    <th className="px-6 py-4 font-semibold">Status</th>
                    <th className="px-6 py-4 font-semibold">Last Backup</th>
                    <th className="px-6 py-4 font-semibold">Version</th>
                    <th className="px-6 py-4 font-semibold text-right">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border-dark text-sm">
                  {clients.map((client, idx) => {
                    const isExpanded = expandedRows.has(client.client_id)
                    const isSelected = selectedClients.has(client.client_id)
                    const backupStatus = getLastBackupStatus(client)
                    const connection = getConnectionInfo(client)
                    const isOnline = client.status === 'online'
                    
                    return (
                      <>
                        <tr 
                          key={client.client_id || client.name} 
                          className={`hover:bg-surface-dark/50 transition-colors group ${
                            idx % 2 === 0 ? 'bg-surface-dark/20' : ''
                          } ${!isOnline ? 'bg-red-500/5' : ''}`}
                        >
                          <td className="px-6 py-4">
                            <input 
                              type="checkbox" 
                              className="checkbox-custom"
                              checked={isSelected}
                              onChange={() => toggleSelectClient(client.client_id)}
                            />
                          </td>
                          <td className="px-2 py-4 text-center">
                            <button 
                              onClick={() => toggleRow(client.client_id)}
                              className="text-text-secondary hover:text-white transition-colors"
                            >
                              <span className={`material-symbols-outlined text-[20px] transition-transform ${isExpanded ? 'transform rotate-90' : ''}`}>
                                chevron_right
                              </span>
                            </button>
                          </td>
                          <td className="px-6 py-4">
                            <div className="flex items-center gap-3">
                              <div className="h-8 w-8 rounded bg-surface-dark flex items-center justify-center text-text-secondary border border-border-dark">
                                <span className="material-symbols-outlined text-[20px]">dns</span>
                              </div>
                              <div>
                                <p className="text-white font-bold">{client.name}</p>
                                <p className="text-text-secondary text-xs">{client.uname || 'Backup Client'}</p>
                              </div>
                            </div>
                          </td>
                          <td className="px-6 py-4">
                            {client.category ? (
                              <span className={`inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium border ${
                                client.category === 'File' 
                                  ? 'bg-blue-500/10 text-blue-400 border-blue-500/20' 
                                  : client.category === 'Database'
                                  ? 'bg-purple-500/10 text-purple-400 border-purple-500/20'
                                  : 'bg-orange-500/10 text-orange-400 border-orange-500/20'
                              }`}>
                                {client.category === 'File' && <span className="material-symbols-outlined text-[12px]">folder</span>}
                                {client.category === 'Database' && <span className="material-symbols-outlined text-[12px]">storage</span>}
                                {client.category === 'Virtual' && <span className="material-symbols-outlined text-[12px]">computer</span>}
                                {client.category}
                              </span>
                            ) : (
                              <span className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium bg-surface-dark text-text-secondary border border-border-dark">
                                File
                              </span>
                            )}
                          </td>
                          <td className="px-6 py-4">
                            <div className="flex flex-col gap-0.5">
                              <p className="text-text-secondary font-mono text-xs">{connection.ip}</p>
                              <p className="text-text-secondary/60 text-[10px]">Port: {connection.port}</p>
                            </div>
                          </td>
                          <td className="px-6 py-4">
                            {isOnline ? (
                              <span className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium bg-green-500/10 text-green-400 border border-green-500/20">
                                <span className="block h-1.5 w-1.5 rounded-full bg-green-400"></span>
                                Online
                              </span>
                            ) : (
                              <span className="inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-xs font-medium bg-red-500/10 text-red-400 border border-red-500/20">
                                <span className="material-symbols-outlined text-[12px]">link_off</span>
                                Offline
                              </span>
                            )}
                          </td>
                          <td className="px-6 py-4">
                            <div className="flex flex-col">
                              <div className={`flex items-center gap-1.5 ${
                                backupStatus.status === 'success' ? 'text-green-400' :
                                backupStatus.status === 'failed' ? 'text-red-400' :
                                backupStatus.status === 'running' ? 'text-primary' :
                                'text-yellow-500'
                              }`}>
                                {backupStatus.status === 'success' && <span className="material-symbols-outlined text-[14px]">check_circle</span>}
                                {backupStatus.status === 'failed' && <span className="material-symbols-outlined text-[14px]">error</span>}
                                {backupStatus.status === 'running' && <span className="block h-2 w-2 rounded-full bg-primary animate-pulse"></span>}
                                {backupStatus.status === 'warning' && <span className="material-symbols-outlined text-[14px]">warning</span>}
                                <span className="font-bold text-xs">{backupStatus.text}</span>
                              </div>
                              <p className="text-text-secondary text-xs mt-0.5">{backupStatus.time}</p>
                            </div>
                          </td>
                          <td className="px-6 py-4">
                            <span className="text-text-secondary font-mono text-xs bg-surface-dark px-2 py-1 rounded border border-border-dark">
                              v22.4.1
                            </span>
                          </td>
                          <td className="px-6 py-4 text-right">
                            <div className="flex items-center justify-end gap-2 opacity-0 group-hover:opacity-100 transition-opacity relative">
                              <button 
                                onClick={() => handleStartBackup(client)}
                                disabled={isStartingBackup === client.client_id}
                                className="p-1.5 text-text-secondary hover:text-white hover:bg-surface-dark rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed" 
                                title="Start Backup"
                              >
                                {isStartingBackup === client.client_id ? (
                                  <span className="material-symbols-outlined text-[20px] animate-spin">refresh</span>
                                ) : (
                                  <span className="material-symbols-outlined text-[20px]">play_arrow</span>
                                )}
                              </button>
                              <button 
                                onClick={() => handleEditConfig(client)}
                                className="p-1.5 text-text-secondary hover:text-white hover:bg-surface-dark rounded transition-colors" 
                                title="Edit Config"
                              >
                                <span className="material-symbols-outlined text-[20px]">edit</span>
                              </button>
                              <div className="relative">
                                <button 
                                  onClick={() => toggleMenu(client.client_id)}
                                  className="menu-trigger p-1.5 text-text-secondary hover:text-white hover:bg-surface-dark rounded transition-colors"
                                  title="More Options"
                                >
                                  <span className="material-symbols-outlined text-[20px]">more_vert</span>
                                </button>
                                {openMenuId === client.client_id && (
                                  <div className="dropdown-menu absolute right-0 mt-1 w-48 bg-surface-dark border border-border-dark rounded-lg shadow-lg z-50 py-1">
                                    <button
                                      onClick={() => {
                                        handleStartBackup(client)
                                        setOpenMenuId(null)
                                      }}
                                      className="w-full text-left px-4 py-2 text-sm text-white hover:bg-surface-highlight flex items-center gap-2"
                                    >
                                      <span className="material-symbols-outlined text-[18px]">play_arrow</span>
                                      Start Backup
                                    </button>
                                    <button
                                      onClick={() => {
                                        handleEditConfig(client)
                                        setOpenMenuId(null)
                                      }}
                                      className="w-full text-left px-4 py-2 text-sm text-white hover:bg-surface-highlight flex items-center gap-2"
                                    >
                                      <span className="material-symbols-outlined text-[18px]">edit</span>
                                      Edit Config
                                    </button>
                                    <button
                                      onClick={() => {
                                        const command = `status client=${client.name}`
                                        if (onSwitchToConsole) {
                                          onSwitchToConsole()
                                          setTimeout(() => {
                                            const consoleInput = document.querySelector('input[data-console-input]') as HTMLInputElement
                                            if (consoleInput) {
                                              const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set
                                              if (nativeInputValueSetter) {
                                                nativeInputValueSetter.call(consoleInput, command)
                                                const event = new Event('input', { bubbles: true })
                                                consoleInput.dispatchEvent(event)
                                              } else {
                                                consoleInput.value = command
                                                consoleInput.dispatchEvent(new Event('input', { bubbles: true }))
                                              }
                                              consoleInput.focus()
                                            }
                                          }, 200)
                                        }
                                        setOpenMenuId(null)
                                      }}
                                      className="w-full text-left px-4 py-2 text-sm text-white hover:bg-surface-highlight flex items-center gap-2"
                                    >
                                      <span className="material-symbols-outlined text-[18px]">info</span>
                                      View Status
                                    </button>
                                    <button
                                      onClick={() => {
                                        const command = `list jobs client=${client.name}`
                                        if (onSwitchToConsole) {
                                          onSwitchToConsole()
                                          setTimeout(() => {
                                            const consoleInput = document.querySelector('input[data-console-input]') as HTMLInputElement
                                            if (consoleInput) {
                                              const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set
                                              if (nativeInputValueSetter) {
                                                nativeInputValueSetter.call(consoleInput, command)
                                                const event = new Event('input', { bubbles: true })
                                                consoleInput.dispatchEvent(event)
                                              } else {
                                                consoleInput.value = command
                                                consoleInput.dispatchEvent(new Event('input', { bubbles: true }))
                                              }
                                              consoleInput.focus()
                                            }
                                          }, 200)
                                        }
                                        setOpenMenuId(null)
                                      }}
                                      className="w-full text-left px-4 py-2 text-sm text-white hover:bg-surface-highlight flex items-center gap-2"
                                    >
                                      <span className="material-symbols-outlined text-[18px]">history</span>
                                      View Jobs
                                    </button>
                                    <div className="border-t border-border-dark my-1"></div>
                                    <button
                                      onClick={() => {
                                        if (confirm(`Are you sure you want to disable client "${client.name}"?`)) {
                                          const command = `disable client=${client.name}`
                                          backupAPI.executeBconsoleCommand(command).then(() => {
                                            queryClient.invalidateQueries({ queryKey: ['backup-clients'] })
                                            setOpenMenuId(null)
                                          }).catch((err) => {
                                            alert(`Failed to disable client: ${err.message}`)
                                          })
                                        }
                                      }}
                                      className="w-full text-left px-4 py-2 text-sm text-red-400 hover:bg-surface-highlight flex items-center gap-2"
                                    >
                                      <span className="material-symbols-outlined text-[18px]">block</span>
                                      Disable Client
                                    </button>
                                  </div>
                                )}
                              </div>
                            </div>
                          </td>
                        </tr>
                        {isExpanded && (
                          <tr className="bg-surface-dark/10">
                            <td className="p-0 border-b border-border-dark" colSpan={9}>
                              <div className="flex flex-col pl-16 py-2 pr-6 border-l-4 border-primary/50 ml-[26px]">
                                <div className="flex items-center gap-2 mb-3">
                                  <span className="text-xs font-bold text-text-secondary uppercase tracking-wider">Installed Agents & Plugins</span>
                                  <div className="h-px bg-border-dark flex-1"></div>
                                </div>
                                <div className="grid grid-cols-1 gap-2">
                                  <div className="relative pl-12 agent-item">
                                    <div className="tree-line-vertical"></div>
                                    <div className="tree-line-horizontal"></div>
                                    <div className="flex items-center justify-between p-3 rounded-lg bg-surface-dark border border-border-dark hover:border-primary/50 transition-colors">
                                      <div className="flex items-center gap-3">
                                        <div className="p-1.5 rounded bg-blue-500/10 text-blue-400">
                                          <span className="material-symbols-outlined text-[18px]">folder_open</span>
                                        </div>
                                        <div className="flex flex-col">
                                          <p className="text-white text-sm font-bold">Standard File Daemon</p>
                                          <p className="text-text-secondary text-xs">Core Bacula Client</p>
                                        </div>
                                      </div>
                                      <div className="flex items-center gap-6">
                                        <div className="flex items-center gap-2 px-2 py-1 rounded bg-surface-highlight border border-border-dark/50">
                                          <span className="text-[10px] text-text-secondary uppercase font-bold">Ver</span>
                                          <span className="text-xs text-white font-mono">22.4.1</span>
                                        </div>
                                        <div className="flex items-center gap-1.5 text-green-400">
                                          <span className="material-symbols-outlined text-[16px]">check_circle</span>
                                          <span className="text-xs font-bold">Active</span>
                                        </div>
                                      </div>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </td>
                          </tr>
                        )}
                      </>
                    )
                  })}
                </tbody>
              </table>
            </div>
            <div className="bg-surface-dark border-t border-border-dark px-6 py-3 flex items-center justify-between mt-auto">
              <p className="text-text-secondary text-xs">Showing {clients.length} of {total} clients</p>
              <div className="flex gap-2">
                <button className="p-1 rounded text-text-secondary opacity-50 cursor-not-allowed" disabled>
                  <span className="material-symbols-outlined text-base">chevron_left</span>
                </button>
                <button className="p-1 rounded text-text-secondary hover:text-white hover:bg-surface-highlight">
                  <span className="material-symbols-outlined text-base">chevron_right</span>
                </button>
              </div>
            </div>
          </>
        )}
      </div>

      {/* Console Log */}
      <div className="mt-4">
        <div className="rounded-lg bg-[#0d131a] border border-border-dark p-4 font-mono text-xs text-text-secondary shadow-inner h-32 overflow-y-auto">
          <div className="flex items-center justify-between mb-2 text-gray-500 border-b border-white/5 pb-1">
            <span>Console Log (tail -f)</span>
            <span className="flex items-center gap-1">
              <span className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></span> Connected
            </span>
          </div>
          <p className="text-blue-400">[14:22:01] bareos-dir: Connected to Storage at backup-srv-01:9103</p>
          <p>[14:22:02] bareos-sd: Volume "Vol-0012" selected for appending</p>
          <p>[14:22:05] bareos-fd: Client "{clients[0]?.name || 'client'}" starting backup of /var/www/html</p>
          <p className="text-yellow-500">[14:23:10] warning: /var/www/html/cache/tmp locked by another process, skipping</p>
          <p>[14:23:45] bareos-dir: JobId 10423: Sending Accurate information.</p>
        </div>
        </div>
      </div>
    </>
  )
}

function StorageManagementTab() {
  const location = useLocation()
  const searchParams = new URLSearchParams(location.search)
  const viewFromUrl = searchParams.get('view') as 'pools' | 'volumes' | 'daemons' | null
  
  const [activeView, setActiveView] = useState<'pools' | 'volumes' | 'daemons'>(
    viewFromUrl || 'pools'
  )
  
  // Sync activeView with URL query parameter when URL changes
  useEffect(() => {
    const currentView = new URLSearchParams(location.search).get('view') as typeof activeView | null
    const newView = currentView || 'pools'
    if (newView !== activeView && (newView === 'pools' || newView === 'volumes' || newView === 'daemons')) {
      setActiveView(newView)
    }
  }, [location.search])
  
  // Helper function to change view and update URL
  const changeView = (view: typeof activeView) => {
    setActiveView(view)
    const newSearchParams = new URLSearchParams(location.search)
    // Ensure tab=storage is set
    newSearchParams.set('tab', 'storage')
    if (view === 'pools') {
      newSearchParams.delete('view')
    } else {
      newSearchParams.set('view', view)
    }
    const newUrl = `${location.pathname}?${newSearchParams.toString()}`
    window.history.replaceState({}, '', newUrl)
  }
  const [poolAction, setPoolAction] = useState<'list' | 'add' | 'delete'>('list')
  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const [poolToDelete, setPoolToDelete] = useState<StoragePool | null>(null)
  const queryClient = useQueryClient()

  // Fetch storage pools
  const { data: poolsData, isLoading: poolsLoading } = useQuery({
    queryKey: ['storage-pools'],
    queryFn: () => backupAPI.listStoragePools(),
  })

  // Create pool mutation
  const createPoolMutation = useMutation({
    mutationFn: backupAPI.createStoragePool,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['storage-pools'] })
      setPoolAction('list')
    },
  })

  // Delete pool mutation
  const deletePoolMutation = useMutation({
    mutationFn: backupAPI.deleteStoragePool,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['storage-pools'] })
      setShowDeleteModal(false)
      setPoolToDelete(null)
    },
  })

  // Fetch storage daemons
  const { data: daemonsData, isLoading: daemonsLoading } = useQuery({
    queryKey: ['storage-daemons'],
    queryFn: () => backupAPI.listStorageDaemons(),
    enabled: activeView === 'daemons',
  })

  const pools = poolsData?.pools || []
  const daemons = daemonsData?.daemons || []

  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 `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`
  }

  const getStatusBadge = (status: string) => {
    const statusMap: Record<string, { bg: string; text: string; border: string }> = {
      Full: { bg: 'bg-green-500/10', text: 'text-green-400', border: 'border-green-500/20' },
      Append: { bg: 'bg-blue-500/10', text: 'text-blue-400', border: 'border-blue-500/20' },
      Used: { bg: 'bg-yellow-500/10', text: 'text-yellow-400', border: 'border-yellow-500/20' },
      Error: { bg: 'bg-red-500/10', text: 'text-red-400', border: 'border-red-500/20' },
      Online: { bg: 'bg-green-500/10', text: 'text-green-400', border: 'border-green-500/20' },
      Offline: { bg: 'bg-red-500/10', text: 'text-red-400', border: 'border-red-500/20' },
    }
    const config = statusMap[status] || { bg: 'bg-gray-500/10', text: 'text-gray-400', border: 'border-gray-500/20' }
    return (
      <span className={`inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs font-medium ${config.bg} ${config.text} border ${config.border}`}>
        {status}
      </span>
    )
  }

  return (
    <div className="flex flex-col gap-6 flex-1">
      {/* Header */}
      <header className="flex flex-wrap justify-between items-end gap-4 border-b border-border-dark pb-6">
        <div className="flex flex-col gap-2">
          <div className="flex items-center gap-3">
            <h1 className="text-white text-3xl md:text-4xl font-black leading-tight tracking-tight">Storage Management</h1>
            <span className="flex h-6 px-2 items-center rounded-full bg-surface-highlight border border-border-dark text-xs font-bold text-primary">
              {pools.length} Pools
            </span>
          </div>
          <p className="text-text-secondary text-base font-normal max-w-2xl">
            Manage storage pools, volumes, and storage daemons for backup operations.
          </p>
        </div>
      </header>

      {/* Tabs */}
      <div className="w-full overflow-x-auto">
        <div className="flex border-b border-border-dark gap-8 min-w-max">
          <button
            onClick={() => changeView('pools')}
            className={`flex items-center gap-2 border-b-[3px] pb-3 pt-2 transition-colors ${
              activeView === 'pools'
                ? 'border-primary text-white'
                : 'border-transparent text-text-secondary hover:text-white'
            }`}
          >
            <span className="material-symbols-outlined text-base">hard_drive</span>
            <p className="text-sm font-bold tracking-wide">Pools</p>
          </button>
          <button
            onClick={() => changeView('volumes')}
            className={`flex items-center gap-2 border-b-[3px] pb-3 pt-2 transition-colors ${
              activeView === 'volumes'
                ? 'border-primary text-white'
                : 'border-transparent text-text-secondary hover:text-white'
            }`}
          >
            <span className="material-symbols-outlined text-base">storage</span>
            <p className="text-sm font-bold tracking-wide">Volumes</p>
          </button>
          <button
            onClick={() => changeView('daemons')}
            className={`flex items-center gap-2 border-b-[3px] pb-3 pt-2 transition-colors ${
              activeView === 'daemons'
                ? 'border-primary text-white'
                : 'border-transparent text-text-secondary hover:text-white'
            }`}
          >
            <span className="material-symbols-outlined text-base">dns</span>
            <p className="text-sm font-bold tracking-wide">Storage Daemons</p>
          </button>
        </div>
      </div>

      {/* Content */}
      {activeView === 'pools' && (
        <div className="flex flex-col gap-4">
          {/* Pool Actions Tabs */}
          <div className="flex items-center gap-4 border-b border-border-dark pb-4">
            <button
              onClick={() => setPoolAction('list')}
              className={`px-4 py-2 rounded-lg text-sm font-bold transition-colors ${
                poolAction === 'list'
                  ? 'bg-primary text-white'
                  : 'bg-surface-highlight text-text-secondary hover:text-white hover:bg-[#2a3c50]'
              }`}
            >
              <span className="material-symbols-outlined text-base mr-2 align-middle">list</span>
              List Current Pools
            </button>
            <button
              onClick={() => setPoolAction('add')}
              className={`px-4 py-2 rounded-lg text-sm font-bold transition-colors ${
                poolAction === 'add'
                  ? 'bg-primary text-white'
                  : 'bg-surface-highlight text-text-secondary hover:text-white hover:bg-[#2a3c50]'
              }`}
            >
              <span className="material-symbols-outlined text-base mr-2 align-middle">add</span>
              Add Pool
            </button>
            <button
              onClick={() => setPoolAction('delete')}
              className={`px-4 py-2 rounded-lg text-sm font-bold transition-colors ${
                poolAction === 'delete'
                  ? 'bg-primary text-white'
                  : 'bg-surface-highlight text-text-secondary hover:text-white hover:bg-[#2a3c50]'
              }`}
            >
              <span className="material-symbols-outlined text-base mr-2 align-middle">delete</span>
              Delete Pool
            </button>
          </div>

          {/* List Pools View */}
          {poolAction === 'list' && (
            <div className="rounded-lg border border-border-dark bg-surface-highlight overflow-hidden shadow-sm">
          {poolsLoading ? (
            <div className="p-8 text-center text-text-secondary">Loading pools...</div>
          ) : pools.length === 0 ? (
            <div className="p-12 text-center">
              <p className="text-text-secondary">No storage pools found</p>
            </div>
          ) : (
            <>
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse">
                  <thead>
                    <tr className="bg-surface-dark border-b border-border-dark text-text-secondary text-xs uppercase tracking-wider">
                      <th className="px-6 py-4 font-semibold">Pool Name</th>
                      <th className="px-6 py-4 font-semibold">Type</th>
                      <th className="px-6 py-4 font-semibold">Volumes</th>
                      <th className="px-6 py-4 font-semibold">Usage</th>
                      <th className="px-6 py-4 font-semibold">Capacity</th>
                      <th className="px-6 py-4 font-semibold">Options</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border-dark text-sm">
                    {pools.map((pool) => (
                      <tr key={pool.pool_id} className="hover:bg-surface-dark/50 transition-colors">
                        <td className="px-6 py-4">
                          <div className="flex items-center gap-3">
                            <div className="h-8 w-8 rounded bg-surface-dark flex items-center justify-center text-primary border border-border-dark">
                              <span className="material-symbols-outlined text-[20px]">hard_drive</span>
                            </div>
                            <div>
                              <p className="text-white font-bold">{pool.name}</p>
                              {pool.label_format && (
                                <p className="text-text-secondary text-xs">{pool.label_format}</p>
                              )}
                            </div>
                          </div>
                        </td>
                        <td className="px-6 py-4 text-text-secondary">{pool.pool_type || '-'}</td>
                        <td className="px-6 py-4 text-text-secondary">{pool.volume_count}</td>
                        <td className="px-6 py-4">
                          <div className="flex flex-col gap-1">
                            <div className="flex items-center justify-between">
                              <span className="text-white text-xs font-bold">{Math.round(pool.usage_percent)}%</span>
                            </div>
                            <div className="w-full bg-[#111a22] h-2 rounded-full overflow-hidden">
                              <div
                                className="bg-gradient-to-r from-primary to-blue-400 h-full rounded-full"
                                style={{ width: `${Math.min(pool.usage_percent, 100)}%` }}
                              ></div>
                            </div>
                          </div>
                        </td>
                        <td className="px-6 py-4 text-text-secondary font-mono text-xs">
                          {formatBytes(pool.used_bytes)} / {formatBytes(pool.total_bytes)}
                        </td>
                        <td className="px-6 py-4">
                          <div className="flex items-center gap-2">
                            {pool.recycle && (
                              <span className="text-xs text-text-secondary">Recycle</span>
                            )}
                            {pool.auto_prune && (
                              <span className="text-xs text-text-secondary">Auto-Prune</span>
                            )}
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </>
          )}
        </div>
          )}

          {/* Add Pool View */}
          {poolAction === 'add' && (
            <div className="rounded-lg border border-border-dark bg-surface-highlight p-6">
              <h3 className="text-white text-xl font-bold mb-4">Create New Storage Pool</h3>
              <p className="text-text-secondary text-sm mb-6">
                Pools define the set of storage Volumes to be used by Bacula. Configure different pools to organize your backup data.
              </p>
              <AddPoolForm
                onSubmit={(data) => {
                  createPoolMutation.mutate(data)
                }}
                isLoading={createPoolMutation.isPending}
                onCancel={() => setPoolAction('list')}
              />
            </div>
          )}

          {/* Delete Pool View */}
          {poolAction === 'delete' && (
            <div className="rounded-lg border border-border-dark bg-surface-highlight overflow-hidden shadow-sm">
              {poolsLoading ? (
                <div className="p-8 text-center text-text-secondary">Loading pools...</div>
              ) : pools.length === 0 ? (
                <div className="p-12 text-center">
                  <p className="text-text-secondary">No storage pools found</p>
                </div>
              ) : (
                <>
                  <div className="p-4 border-b border-border-dark">
                    <p className="text-text-secondary text-sm mb-4">
                      Select a pool to delete. Pools with volumes cannot be deleted.
                    </p>
                  </div>
                  <div className="overflow-x-auto">
                    <table className="w-full text-left border-collapse">
                      <thead>
                        <tr className="bg-surface-dark border-b border-border-dark text-text-secondary text-xs uppercase tracking-wider">
                          <th className="px-6 py-4 font-semibold">Pool Name</th>
                          <th className="px-6 py-4 font-semibold">Type</th>
                          <th className="px-6 py-4 font-semibold">Volumes</th>
                          <th className="px-6 py-4 font-semibold">Usage</th>
                          <th className="px-6 py-4 font-semibold text-right">Actions</th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-border-dark text-sm">
                        {pools.map((pool) => (
                          <tr key={pool.pool_id} className="hover:bg-surface-dark/50 transition-colors">
                            <td className="px-6 py-4">
                              <div className="flex items-center gap-3">
                                <div className="h-8 w-8 rounded bg-surface-dark flex items-center justify-center text-primary border border-border-dark">
                                  <span className="material-symbols-outlined text-[20px]">hard_drive</span>
                                </div>
                                <p className="text-white font-bold">{pool.name}</p>
                              </div>
                            </td>
                            <td className="px-6 py-4 text-text-secondary">{pool.pool_type || '-'}</td>
                            <td className="px-6 py-4 text-text-secondary">{pool.volume_count}</td>
                            <td className="px-6 py-4">
                              <div className="flex items-center gap-2">
                                <span className="text-white text-xs font-bold">{Math.round(pool.usage_percent)}%</span>
                                <div className="w-24 bg-[#111a22] h-2 rounded-full overflow-hidden">
                                  <div
                                    className="bg-gradient-to-r from-primary to-blue-400 h-full rounded-full"
                                    style={{ width: `${Math.min(pool.usage_percent, 100)}%` }}
                                  ></div>
                                </div>
                              </div>
                            </td>
                            <td className="px-6 py-4 text-right">
                              <button
                                onClick={() => {
                                  setPoolToDelete(pool)
                                  setShowDeleteModal(true)
                                }}
                                disabled={pool.volume_count > 0}
                                className={`px-4 py-2 rounded-lg text-sm font-bold transition-colors ${
                                  pool.volume_count > 0
                                    ? 'bg-gray-500/20 text-gray-500 cursor-not-allowed'
                                    : 'bg-red-500/10 text-red-400 hover:bg-red-500/20 border border-red-500/20'
                                }`}
                                title={pool.volume_count > 0 ? 'Cannot delete pool with volumes' : 'Delete pool'}
                              >
                                <span className="material-symbols-outlined text-base mr-1 align-middle">delete</span>
                                Delete
                              </button>
                            </td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                </>
              )}
            </div>
          )}
        </div>
      )}

      {activeView === 'volumes' && (
        <VolumeManagementTab pools={pools} />
      )}

      {activeView === 'daemons' && (
        <div className="rounded-lg border border-border-dark bg-surface-highlight overflow-hidden shadow-sm">
          {daemonsLoading ? (
            <div className="p-8 text-center text-text-secondary">Loading storage daemons...</div>
          ) : daemons.length === 0 ? (
            <div className="p-12 text-center">
              <p className="text-text-secondary">No storage daemons found</p>
            </div>
          ) : (
            <>
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse">
                  <thead>
                    <tr className="bg-surface-dark border-b border-border-dark text-text-secondary text-xs uppercase tracking-wider">
                      <th className="px-6 py-4 font-semibold">Name</th>
                      <th className="px-6 py-4 font-semibold">Address</th>
                      <th className="px-6 py-4 font-semibold">Port</th>
                      <th className="px-6 py-4 font-semibold">Device</th>
                      <th className="px-6 py-4 font-semibold">Media Type</th>
                      <th className="px-6 py-4 font-semibold">Status</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border-dark text-sm">
                    {daemons.map((daemon) => (
                      <tr key={daemon.storage_id} className="hover:bg-surface-dark/50 transition-colors">
                        <td className="px-6 py-4">
                          <div className="flex items-center gap-3">
                            <div className="h-8 w-8 rounded bg-surface-dark flex items-center justify-center text-primary border border-border-dark">
                              <span className="material-symbols-outlined text-[20px]">dns</span>
                            </div>
                            <p className="text-white font-bold">{daemon.name}</p>
                          </div>
                        </td>
                        <td className="px-6 py-4 text-text-secondary font-mono text-xs">{daemon.address}</td>
                        <td className="px-6 py-4 text-text-secondary">{daemon.port}</td>
                        <td className="px-6 py-4 text-text-secondary">{daemon.device_name}</td>
                        <td className="px-6 py-4 text-text-secondary">{daemon.media_type}</td>
                        <td className="px-6 py-4">{getStatusBadge(daemon.status)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </>
          )}
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {showDeleteModal && poolToDelete && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-surface-highlight border border-border-dark rounded-lg p-6 max-w-md w-full mx-4">
            <h3 className="text-white text-xl font-bold mb-2">Delete Storage Pool</h3>
            <p className="text-text-secondary text-sm mb-4">
              Are you sure you want to delete pool <span className="text-white font-bold">{poolToDelete.name}</span>?
            </p>
            {poolToDelete.volume_count > 0 && (
              <div className="bg-red-500/10 border border-red-500/20 rounded-lg p-3 mb-4">
                <p className="text-red-400 text-sm">
                  ⚠️ This pool contains {poolToDelete.volume_count} volume(s). Pools with volumes cannot be deleted.
                </p>
              </div>
            )}
            <div className="flex gap-3 justify-end">
              <button
                onClick={() => {
                  setShowDeleteModal(false)
                  setPoolToDelete(null)
                }}
                className="px-4 py-2 rounded-lg bg-surface-dark border border-border-dark text-white text-sm font-bold hover:bg-[#2a3c50] transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={() => {
                  if (poolToDelete.volume_count === 0) {
                    deletePoolMutation.mutate(poolToDelete.pool_id)
                  }
                }}
                disabled={poolToDelete.volume_count > 0 || deletePoolMutation.isPending}
                className="px-4 py-2 rounded-lg bg-red-500 text-white text-sm font-bold hover:bg-red-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {deletePoolMutation.isPending ? 'Deleting...' : 'Delete Pool'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

function AddPoolForm({ onSubmit, isLoading, onCancel }: { onSubmit: (data: CreateStoragePoolRequest) => void; isLoading: boolean; onCancel: () => void }) {
  const [formData, setFormData] = useState<CreateStoragePoolRequest>({
    name: '',
    pool_type: 'Backup',
    label_format: '',
    recycle: false,
    auto_prune: false,
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    onSubmit({
      name: formData.name,
      pool_type: formData.pool_type,
      label_format: formData.label_format || undefined,
      recycle: formData.recycle || undefined,
      auto_prune: formData.auto_prune || undefined,
    })
  }

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-4">
      <div>
        <label className="block text-text-secondary text-sm font-medium mb-2">
          Pool Name <span className="text-red-400">*</span>
        </label>
        <input
          type="text"
          required
          value={formData.name}
          onChange={(e) => setFormData({ ...formData, name: e.target.value })}
          placeholder="e.g., Full-Backup, Incremental-Backup"
          className="w-full bg-surface-dark border border-border-dark rounded-lg px-4 py-2 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
        />
        <p className="text-text-secondary text-xs mt-1">Unique name for the storage pool</p>
      </div>

      <div>
        <label className="block text-text-secondary text-sm font-medium mb-2">
          Pool Type <span className="text-red-400">*</span>
        </label>
        <select
          value={formData.pool_type}
          onChange={(e) => setFormData({ ...formData, pool_type: e.target.value })}
          className="w-full bg-surface-dark border border-border-dark rounded-lg px-4 py-2 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
        >
          <option value="Backup">Backup</option>
          <option value="Scratch">Scratch</option>
          <option value="Recycle">Recycle</option>
        </select>
        <p className="text-text-secondary text-xs mt-1">
          {formData.pool_type === 'Backup' && 'Contains volumes for backup data with retention periods'}
          {formData.pool_type === 'Scratch' && 'Contains volumes that can be used by any pool when needed'}
          {formData.pool_type === 'Recycle' && 'Contains volumes that have been purged and are ready for reuse'}
        </p>
      </div>

      <div>
        <label className="block text-text-secondary text-sm font-medium mb-2">
          Label Format
        </label>
        <input
          type="text"
          value={formData.label_format}
          onChange={(e) => setFormData({ ...formData, label_format: e.target.value })}
          placeholder="e.g., Vol-${Year}-${Month:p/2/0/r}-${Day:p/2/0/r}-${Counter:4}"
          className="w-full bg-surface-dark border border-border-dark rounded-lg px-4 py-2 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
        />
        <p className="text-text-secondary text-xs mt-1">Format string for automatic volume labeling</p>
      </div>

      <div className="flex items-center gap-4">
        <label className="flex items-center gap-2 cursor-pointer">
          <input
            type="checkbox"
            checked={formData.recycle || false}
            onChange={(e) => setFormData({ ...formData, recycle: e.target.checked })}
            className="checkbox-custom"
          />
          <span className="text-text-secondary text-sm">Recycle</span>
        </label>
        <label className="flex items-center gap-2 cursor-pointer">
          <input
            type="checkbox"
            checked={formData.auto_prune || false}
            onChange={(e) => setFormData({ ...formData, auto_prune: e.target.checked })}
            className="checkbox-custom"
          />
          <span className="text-text-secondary text-sm">Auto-Prune</span>
        </label>
      </div>

      <div className="flex gap-3 justify-end pt-4 border-t border-border-dark">
        <button
          type="button"
          onClick={onCancel}
          className="px-4 py-2 rounded-lg bg-surface-dark border border-border-dark text-white text-sm font-bold hover:bg-[#2a3c50] transition-colors"
        >
          Cancel
        </button>
        <button
          type="submit"
          disabled={isLoading || !formData.name}
          className="px-4 py-2 rounded-lg bg-primary text-white text-sm font-bold hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {isLoading ? 'Creating...' : 'Create Pool'}
        </button>
      </div>
    </form>
  )
}

function VolumeManagementTab({ pools }: { pools: StoragePool[] }) {
  const [volumeAction, setVolumeAction] = useState<'list' | 'add' | 'delete' | 'update'>('list')
  const [showDeleteModal, setShowDeleteModal] = useState(false)
  const [showUpdateModal, setShowUpdateModal] = useState(false)
  const [volumeToDelete, setVolumeToDelete] = useState<StorageVolume | null>(null)
  const [volumeToUpdate, setVolumeToUpdate] = useState<StorageVolume | null>(null)
  const [selectedVolumes, setSelectedVolumes] = useState<Set<number>>(new Set())
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedVolume, setSelectedVolume] = useState<number | null>(null)
  const [currentPage, setCurrentPage] = useState(1)
  const itemsPerPage = 5
  const queryClient = useQueryClient()

  // Fetch media from bconsole "list media" command
  const { data: mediaData, isLoading: mediaLoading } = useQuery({
    queryKey: ['backup-media'],
    queryFn: () => backupAPI.listMedia(),
    enabled: volumeAction === 'list',
    refetchOnWindowFocus: false,
  })

  // Fetch storage volumes (for add/delete/update operations)
  const { data: volumesData, isLoading: volumesLoading } = useQuery({
    queryKey: ['storage-volumes'],
    queryFn: () => backupAPI.listStorageVolumes(),
    enabled: volumeAction !== 'list',
  })

  // Create volume mutation
  const createVolumeMutation = useMutation({
    mutationFn: backupAPI.createStorageVolume,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['storage-volumes'] })
      setVolumeAction('list')
    },
  })

  // Update volume mutation
  const updateVolumeMutation = useMutation({
    mutationFn: ({ volumeId, data }: { volumeId: number; data: any }) => backupAPI.updateStorageVolume(volumeId, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['storage-volumes'] })
      setShowUpdateModal(false)
      setVolumeToUpdate(null)
    },
  })

  // Delete volume mutation
  const deleteVolumeMutation = useMutation({
    mutationFn: backupAPI.deleteStorageVolume,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['storage-volumes'] })
      setShowDeleteModal(false)
      setVolumeToDelete(null)
    },
  })

  const media = mediaData?.media || []
  const volumes = volumesData?.volumes || []

  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 `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`
  }

  const getStatusBadge = (status: string) => {
    const statusMap: Record<string, { bg: string; text: string; border: string }> = {
      Full: { bg: 'bg-green-500/10', text: 'text-green-400', border: 'border-green-500/20' },
      Append: { bg: 'bg-blue-500/10', text: 'text-blue-400', border: 'border-blue-500/20' },
      Used: { bg: 'bg-yellow-500/10', text: 'text-yellow-400', border: 'border-yellow-500/20' },
      Error: { bg: 'bg-red-500/10', text: 'text-red-400', border: 'border-red-500/20' },
      Recycle: { bg: 'bg-gray-500/10', text: 'text-gray-400', border: 'border-gray-500/20' },
      Purged: { bg: 'bg-gray-500/10', text: 'text-gray-400', border: 'border-gray-500/20' },
      Online: { bg: 'bg-green-500/10', text: 'text-green-400', border: 'border-green-500/20' },
      Offline: { bg: 'bg-red-500/10', text: 'text-red-400', border: 'border-red-500/20' },
    }
    const config = statusMap[status] || { bg: 'bg-gray-500/10', text: 'text-gray-400', border: 'border-gray-500/20' }
    return (
      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${config.bg} ${config.text} border ${config.border}`}>
        {status}
      </span>
    )
  }

  // Filter and paginate media
  const filteredMedia = media.filter((m) => {
    if (!searchQuery) return true
    const query = searchQuery.toLowerCase()
    return (
      m.volume_name.toLowerCase().includes(query) ||
      m.pool_name.toLowerCase().includes(query) ||
      m.status.toLowerCase().includes(query) ||
      m.media_type.toLowerCase().includes(query)
    )
  })

  const totalPages = Math.ceil(filteredMedia.length / itemsPerPage)
  const startIndex = (currentPage - 1) * itemsPerPage
  const endIndex = startIndex + itemsPerPage
  const paginatedMedia = filteredMedia.slice(startIndex, endIndex)


  const formatDate = (dateStr?: string): string => {
    if (!dateStr) return '-'
    try {
      const date = new Date(dateStr)
      return date.toLocaleString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
    } catch {
      return dateStr
    }
  }

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedVolumes(new Set(paginatedMedia.map((m) => m.media_id)))
    } else {
      setSelectedVolumes(new Set())
    }
  }

  const handleSelectVolume = (mediaId: number, checked: boolean) => {
    const newSelected = new Set(selectedVolumes)
    if (checked) {
      newSelected.add(mediaId)
    } else {
      newSelected.delete(mediaId)
    }
    setSelectedVolumes(newSelected)
  }

  const selectedMedia = media.find((m) => m.media_id === selectedVolume)

  return (
    <div className="flex flex-col gap-4">
      {/* Action Buttons and Search */}
      <div className="flex flex-col md:flex-row gap-4 mb-6">
        <button
          onClick={() => setVolumeAction('list')}
          className="bg-primary hover:bg-primary/90 text-white px-5 py-2 rounded shadow-sm flex items-center gap-2 text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"
        >
          <span className="material-symbols-outlined text-lg">format_list_bulleted</span>
          List Current Volumes
        </button>
        <div className="flex gap-2">
          <button
            onClick={() => setVolumeAction('add')}
            className="bg-[#1c2936] border border-border-dark text-white hover:bg-[#2a3c50] px-4 py-2 rounded flex items-center gap-2 text-sm font-medium transition-colors shadow-sm"
          >
            <span className="material-symbols-outlined text-lg text-green-500">add</span>
            Add Volume
          </button>
          <button
            onClick={() => setVolumeAction('delete')}
            className="bg-[#1c2936] border border-border-dark text-white hover:bg-[#2a3c50] px-4 py-2 rounded flex items-center gap-2 text-sm font-medium transition-colors shadow-sm group"
          >
            <span className="material-symbols-outlined text-lg text-red-500 group-hover:text-red-400">delete_outline</span>
            Delete Volume
          </button>
          <button
            onClick={() => setVolumeAction('update')}
            className="bg-[#1c2936] border border-border-dark text-white hover:bg-[#2a3c50] px-4 py-2 rounded flex items-center gap-2 text-sm font-medium transition-colors shadow-sm"
          >
            <span className="material-symbols-outlined text-lg text-text-secondary">edit</span>
            Update Volume
          </button>
        </div>
        <div className="md:ml-auto relative">
          <span className="absolute inset-y-0 left-0 flex items-center pl-3">
            <span className="material-symbols-outlined text-text-secondary text-lg">search</span>
          </span>
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => {
              setSearchQuery(e.target.value)
              setCurrentPage(1)
            }}
            className="w-full md:w-64 bg-[#1c2936] border border-border-dark text-white text-sm rounded pl-10 pr-3 py-2 focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary placeholder-text-secondary shadow-sm"
            placeholder="Filter volumes..."
          />
        </div>
      </div>

      {/* List Media View (from bconsole "list media") */}
      {volumeAction === 'list' && (
        <div className="flex flex-col gap-4">
          {/* Media Table */}
          <div className="bg-[#1c2936] border border-border-dark rounded shadow-sm overflow-hidden">
            <div className="px-6 py-4 border-b border-border-dark bg-[#1c2936] flex justify-between items-center">
              <h2 className="text-sm font-bold uppercase tracking-wider text-text-secondary">Volume Inventory</h2>
              <div className="flex gap-2 text-xs">
                <span className="text-text-secondary">
                  Showing <span className="font-medium">{startIndex + 1}</span> to <span className="font-medium">{Math.min(endIndex, filteredMedia.length)}</span> of{' '}
                  <span className="font-medium">{filteredMedia.length}</span> items
                </span>
              </div>
            </div>
            {mediaLoading ? (
              <div className="p-8 text-center text-text-secondary">Loading media...</div>
            ) : filteredMedia.length === 0 ? (
              <div className="p-12 text-center">
                <p className="text-text-secondary">No media found</p>
              </div>
            ) : (
              <>
                <div className="overflow-x-auto">
                  <table className="w-full text-left text-sm whitespace-nowrap">
                    <thead>
                      <tr className="border-b border-border-dark bg-[#1c2936]">
                        <th className="px-6 py-3 font-semibold text-text-secondary w-10">
                          <input
                            type="checkbox"
                            checked={paginatedMedia.length > 0 && paginatedMedia.every((m) => selectedVolumes.has(m.media_id))}
                            onChange={(e) => handleSelectAll(e.target.checked)}
                            className="rounded border-border-dark text-primary focus:ring-primary bg-[#1c2936]"
                          />
                        </th>
                        <th className="px-6 py-3 font-semibold text-text-secondary cursor-pointer hover:text-primary group">
                          Volume Name <span className="material-symbols-outlined text-xs align-middle opacity-0 group-hover:opacity-100">arrow_downward</span>
                        </th>
                        <th className="px-6 py-3 font-semibold text-text-secondary">Pool</th>
                        <th className="px-6 py-3 font-semibold text-text-secondary">Status</th>
                        <th className="px-6 py-3 font-semibold text-text-secondary">Library</th>
                        <th className="px-6 py-3 font-semibold text-text-secondary text-right">Capacity</th>
                        <th className="px-6 py-3 font-semibold text-text-secondary text-right">Used</th>
                        <th className="px-6 py-3 font-semibold text-text-secondary">Retention</th>
                        <th className="px-6 py-3 font-semibold text-text-secondary text-right">Last Written</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-border-dark">
                      {paginatedMedia.map((m) => {
                        const isSelected = selectedVolume === m.media_id
                        return (
                          <tr
                            key={m.media_id}
                            onClick={() => setSelectedVolume(isSelected ? null : m.media_id)}
                            className={`hover:bg-[#2a3c50] transition-colors cursor-pointer border-l-4 ${
                              isSelected ? 'bg-primary/10 border-l-primary' : 'border-l-transparent'
                            }`}
                          >
                            <td className="px-6 py-4" onClick={(e) => e.stopPropagation()}>
                              <input
                                type="checkbox"
                                checked={isSelected || selectedVolumes.has(m.media_id)}
                                onChange={(e) => {
                                  handleSelectVolume(m.media_id, e.target.checked)
                                  if (e.target.checked) {
                                    setSelectedVolume(m.media_id)
                                  }
                                }}
                                onClick={(e) => e.stopPropagation()}
                                className="rounded border-border-dark text-primary focus:ring-primary bg-[#1c2936]"
                              />
                            </td>
                            <td className="px-6 py-4 font-medium text-white flex items-center gap-2">
                              <span className={`material-symbols-outlined text-lg ${isSelected ? 'text-primary' : 'text-text-secondary'}`}>hard_drive</span>
                              {m.volume_name}
                            </td>
                            <td className="px-6 py-4 text-text-secondary">{m.pool_name}</td>
                            <td className="px-6 py-4">{getStatusBadge(m.status)}</td>
                            <td className="px-6 py-4 text-text-secondary">
                              {m.media_type && (m.media_type.toLowerCase().includes('lto') || m.media_type.toLowerCase().includes('tape')) && m.in_changer && m.in_changer > 0 ? (
                                <span>
                                  {m.library_name || 'Unknown'} {m.slot && m.slot > 0 ? `(Slot ${m.slot})` : ''}
                                </span>
                              ) : (
                                <span className="text-text-secondary/50">-</span>
                              )}
                            </td>
                            <td className="px-6 py-4 text-right text-text-secondary">{formatBytes(m.max_vol_bytes)}</td>
                            <td className="px-6 py-4 text-right text-white font-medium">{formatBytes(m.vol_bytes)}</td>
                            <td className="px-6 py-4 text-text-secondary">
                              {m.max_vol_bytes > 0 && m.vol_bytes > 0 ? '30 Days' : '-'}
                            </td>
                            <td className="px-6 py-4 text-right text-text-secondary text-xs">{formatDate(m.last_written)}</td>
                          </tr>
                        )
                      })}
                    </tbody>
                  </table>
                </div>
                <div className="px-6 py-3 border-t border-border-dark bg-[#1c2936] flex items-center justify-between">
                  <div className="text-xs text-text-secondary">
                    Showing <span className="font-medium">{startIndex + 1}</span> to <span className="font-medium">{Math.min(endIndex, filteredMedia.length)}</span> of{' '}
                    <span className="font-medium">{filteredMedia.length}</span> results
                  </div>
                  <div className="flex gap-1">
                    <button
                      onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
                      disabled={currentPage === 1}
                      className="p-1 rounded hover:bg-[#2a3c50] text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      <span className="material-symbols-outlined text-lg">chevron_left</span>
                    </button>
                    <button
                      onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
                      disabled={currentPage >= totalPages}
                      className="p-1 rounded hover:bg-[#2a3c50] text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      <span className="material-symbols-outlined text-lg">chevron_right</span>
                    </button>
                  </div>
                </div>
              </>
            )}
          </div>

          {/* Volume Details Section */}
          {selectedMedia && (
            <div className="mt-8 bg-[#1c2936] border border-border-dark rounded shadow-sm">
              <div className="px-6 py-4 border-b border-border-dark flex justify-between items-center">
                <h3 className="text-lg font-bold text-white font-display flex items-center gap-2">
                  <span className="material-symbols-outlined text-primary">info</span>
                  Volume Details: {selectedMedia.volume_name}
                </h3>
                <div className="flex gap-2">
                  <button className="text-xs text-primary hover:underline font-medium">View Jobs</button>
                  <span className="text-text-secondary">|</span>
                  <button className="text-xs text-primary hover:underline font-medium">Prune Volume</button>
                </div>
              </div>
              <div className="p-6 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                <div>
                  <span className="block text-xs font-semibold text-text-secondary uppercase tracking-wider mb-1">Volume ID</span>
                  <span className="text-sm text-white">{selectedMedia.media_id}</span>
                </div>
                <div>
                  <span className="block text-xs font-semibold text-text-secondary uppercase tracking-wider mb-1">Media Type</span>
                  <span className="text-sm text-white">{selectedMedia.media_type}</span>
                </div>
                <div>
                  <span className="block text-xs font-semibold text-text-secondary uppercase tracking-wider mb-1">Label Date</span>
                  <span className="text-sm text-white">{formatDate(selectedMedia.last_written) || '-'}</span>
                </div>
                <div>
                  <span className="block text-xs font-semibold text-text-secondary uppercase tracking-wider mb-1">Storage Device</span>
                  <span className="text-sm text-white">{selectedMedia.pool_name}</span>
                </div>
                <div className="col-span-1 md:col-span-2 lg:col-span-4 border-t border-border-dark pt-4 mt-2">
                  <span className="block text-xs font-semibold text-text-secondary uppercase tracking-wider mb-2">Capacity Usage</span>
                  <div className="w-full bg-[#2a3c50] rounded-full h-2.5 mb-1">
                    <div
                      className="bg-primary h-2.5 rounded-full"
                      style={{
                        width: `${
                          selectedMedia.max_vol_bytes > 0
                            ? Math.min(100, (selectedMedia.vol_bytes / selectedMedia.max_vol_bytes) * 100)
                            : 0
                        }%`,
                      }}
                    ></div>
                  </div>
                  <div className="flex justify-between text-xs text-text-secondary">
                    <span>{formatBytes(selectedMedia.vol_bytes)} Used</span>
                    <span>{formatBytes(selectedMedia.max_vol_bytes)} Total</span>
                  </div>
                </div>
              </div>
              <div className="px-6 py-4 bg-[#1c2936] border-t border-border-dark flex justify-end gap-3">
                <button
                  onClick={() => setSelectedVolume(null)}
                  className="px-4 py-2 text-sm font-medium text-text-secondary hover:text-white transition-colors"
                >
                  Close
                </button>
                <button
                  onClick={() => {
                    setVolumeToUpdate({ volume_id: selectedMedia.media_id } as StorageVolume)
                    setShowUpdateModal(true)
                  }}
                  className="bg-primary hover:bg-primary/90 text-white px-4 py-2 rounded text-sm font-medium transition-colors shadow-sm"
                >
                  Edit Properties
                </button>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Add Volume View */}
      {volumeAction === 'add' && (
        <div className="rounded-lg border border-border-dark bg-surface-highlight p-6">
          <h3 className="text-white text-xl font-bold mb-4">Create New Storage Volume</h3>
          <p className="text-text-secondary text-sm mb-6">
            Volumes are archive units where Bacula stores backed up data. Each volume belongs to a Pool and can be a tape or a disk file.
          </p>
          <AddVolumeForm
            pools={pools}
            onSubmit={(data) => {
              createVolumeMutation.mutate(data)
            }}
            isLoading={createVolumeMutation.isPending}
            onCancel={() => setVolumeAction('list')}
          />
        </div>
      )}

      {/* Delete Volume View */}
      {volumeAction === 'delete' && (
        <div className="rounded-lg border border-border-dark bg-surface-highlight overflow-hidden shadow-sm">
          {volumesLoading ? (
            <div className="p-8 text-center text-text-secondary">Loading volumes...</div>
          ) : volumes.length === 0 ? (
            <div className="p-12 text-center">
              <p className="text-text-secondary">No volumes found</p>
            </div>
          ) : (
            <>
              <div className="p-4 border-b border-border-dark">
                <p className="text-text-secondary text-sm mb-4">
                  Select a volume to delete. Volumes with data cannot be deleted.
                </p>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse">
                  <thead>
                    <tr className="bg-surface-dark border-b border-border-dark text-text-secondary text-xs uppercase tracking-wider">
                      <th className="px-6 py-4 font-semibold">Volume Name</th>
                      <th className="px-6 py-4 font-semibold">Pool</th>
                      <th className="px-6 py-4 font-semibold">Status</th>
                      <th className="px-6 py-4 font-semibold">Size</th>
                      <th className="px-6 py-4 font-semibold text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border-dark text-sm">
                    {volumes.map((vol) => (
                      <tr key={vol.volume_id} className="hover:bg-surface-dark/50 transition-colors">
                        <td className="px-6 py-4 text-white font-medium">{vol.volume_name}</td>
                        <td className="px-6 py-4 text-text-secondary">{vol.pool_name}</td>
                        <td className="px-6 py-4">{getStatusBadge(vol.vol_status)}</td>
                        <td className="px-6 py-4 text-text-secondary font-mono text-xs">
                          {formatBytes(vol.vol_bytes)} / {formatBytes(vol.max_vol_bytes)}
                        </td>
                        <td className="px-6 py-4 text-right">
                          <button
                            onClick={() => {
                              setVolumeToDelete(vol)
                              setShowDeleteModal(true)
                            }}
                            disabled={vol.vol_bytes > 0}
                            className={`px-4 py-2 rounded-lg text-sm font-bold transition-colors ${
                              vol.vol_bytes > 0
                                ? 'bg-gray-500/20 text-gray-500 cursor-not-allowed'
                                : 'bg-red-500/10 text-red-400 hover:bg-red-500/20 border border-red-500/20'
                            }`}
                            title={vol.vol_bytes > 0 ? 'Cannot delete volume with data' : 'Delete volume'}
                          >
                            <span className="material-symbols-outlined text-base mr-1 align-middle">delete</span>
                            Delete
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </>
          )}
        </div>
      )}

      {/* Update Volume View */}
      {volumeAction === 'update' && (
        <div className="rounded-lg border border-border-dark bg-surface-highlight overflow-hidden shadow-sm">
          {volumesLoading ? (
            <div className="p-8 text-center text-text-secondary">Loading volumes...</div>
          ) : volumes.length === 0 ? (
            <div className="p-12 text-center">
              <p className="text-text-secondary">No volumes found</p>
            </div>
          ) : (
            <>
              <div className="p-4 border-b border-border-dark">
                <p className="text-text-secondary text-sm mb-4">
                  Select a volume to update its meta-data (Max Volume Bytes, Retention Period).
                </p>
              </div>
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse">
                  <thead>
                    <tr className="bg-surface-dark border-b border-border-dark text-text-secondary text-xs uppercase tracking-wider">
                      <th className="px-6 py-4 font-semibold">Volume Name</th>
                      <th className="px-6 py-4 font-semibold">Pool</th>
                      <th className="px-6 py-4 font-semibold">Status</th>
                      <th className="px-6 py-4 font-semibold">Max Size</th>
                      <th className="px-6 py-4 font-semibold text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border-dark text-sm">
                    {volumes.map((vol) => (
                      <tr key={vol.volume_id} className="hover:bg-surface-dark/50 transition-colors">
                        <td className="px-6 py-4 text-white font-medium">{vol.volume_name}</td>
                        <td className="px-6 py-4 text-text-secondary">{vol.pool_name}</td>
                        <td className="px-6 py-4">{getStatusBadge(vol.vol_status)}</td>
                        <td className="px-6 py-4 text-text-secondary font-mono text-xs">
                          {formatBytes(vol.max_vol_bytes)}
                        </td>
                        <td className="px-6 py-4 text-right">
                          <button
                            onClick={() => {
                              setVolumeToUpdate(vol)
                              setShowUpdateModal(true)
                            }}
                            className="px-4 py-2 rounded-lg text-sm font-bold transition-colors bg-blue-500/10 text-blue-400 hover:bg-blue-500/20 border border-blue-500/20"
                          >
                            <span className="material-symbols-outlined text-base mr-1 align-middle">edit</span>
                            Update
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </>
          )}
        </div>
      )}

      {/* Delete Confirmation Modal */}
      {showDeleteModal && volumeToDelete && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-surface-highlight border border-border-dark rounded-lg p-6 max-w-md w-full mx-4">
            <h3 className="text-white text-xl font-bold mb-2">Delete Storage Volume</h3>
            <p className="text-text-secondary text-sm mb-4">
              Are you sure you want to delete volume <span className="text-white font-bold">{volumeToDelete.volume_name}</span>?
            </p>
            {volumeToDelete.vol_bytes > 0 && (
              <div className="bg-red-500/10 border border-red-500/20 rounded-lg p-3 mb-4">
                <p className="text-red-400 text-sm">
                  ⚠️ This volume contains {formatBytes(volumeToDelete.vol_bytes)} of data. Volumes with data cannot be deleted.
                </p>
              </div>
            )}
            <div className="flex gap-3 justify-end">
              <button
                onClick={() => {
                  setShowDeleteModal(false)
                  setVolumeToDelete(null)
                }}
                className="px-4 py-2 rounded-lg bg-surface-dark border border-border-dark text-white text-sm font-bold hover:bg-[#2a3c50] transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={() => {
                  if (volumeToDelete.vol_bytes === 0) {
                    deleteVolumeMutation.mutate(volumeToDelete.volume_id)
                  }
                }}
                disabled={volumeToDelete.vol_bytes > 0 || deleteVolumeMutation.isPending}
                className="px-4 py-2 rounded-lg bg-red-500 text-white text-sm font-bold hover:bg-red-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {deleteVolumeMutation.isPending ? 'Deleting...' : 'Delete Volume'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Update Modal */}
      {showUpdateModal && volumeToUpdate && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-surface-highlight border border-border-dark rounded-lg p-6 max-w-md w-full mx-4">
            <h3 className="text-white text-xl font-bold mb-2">Update Storage Volume</h3>
            <p className="text-text-secondary text-sm mb-4">
              Update meta-data for volume <span className="text-white font-bold">{volumeToUpdate.volume_name}</span>
            </p>
            <UpdateVolumeForm
              volume={volumeToUpdate}
              onSubmit={(data) => {
                updateVolumeMutation.mutate({ volumeId: volumeToUpdate.volume_id, data })
              }}
              isLoading={updateVolumeMutation.isPending}
              onCancel={() => {
                setShowUpdateModal(false)
                setVolumeToUpdate(null)
              }}
            />
          </div>
        </div>
      )}
    </div>
  )
}

function AddVolumeForm({ pools, onSubmit, isLoading, onCancel }: { pools: StoragePool[]; onSubmit: (data: any) => void; isLoading: boolean; onCancel: () => void }) {
  const [formData, setFormData] = useState({
    volume_name: '',
    pool_name: '',
    media_type: 'File',
    max_vol_bytes: '',
    vol_retention: '',
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    onSubmit({
      volume_name: formData.volume_name,
      pool_name: formData.pool_name,
      media_type: formData.media_type,
      max_vol_bytes: formData.max_vol_bytes ? parseInt(formData.max_vol_bytes) * 1024 * 1024 * 1024 : undefined,
      vol_retention: formData.vol_retention ? parseInt(formData.vol_retention) : undefined,
    })
  }

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-4">
      <div>
        <label className="block text-text-secondary text-sm font-medium mb-2">
          Volume Name <span className="text-red-400">*</span>
        </label>
        <input
          type="text"
          required
          value={formData.volume_name}
          onChange={(e) => setFormData({ ...formData, volume_name: e.target.value })}
          placeholder="e.g., Vol-001, MyBackup-001"
          className="w-full bg-surface-dark border border-border-dark rounded-lg px-4 py-2 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
        />
        <p className="text-text-secondary text-xs mt-1">Unique name for the storage volume</p>
      </div>

      <div>
        <label className="block text-text-secondary text-sm font-medium mb-2">
          Pool <span className="text-red-400">*</span>
        </label>
        <select
          required
          value={formData.pool_name}
          onChange={(e) => setFormData({ ...formData, pool_name: e.target.value })}
          className="w-full bg-surface-dark border border-border-dark rounded-lg px-4 py-2 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
        >
          <option value="">Select a pool</option>
          {pools.map((pool) => (
            <option key={pool.pool_id} value={pool.name}>
              {pool.name}
            </option>
          ))}
        </select>
        <p className="text-text-secondary text-xs mt-1">Pool where this volume will be stored</p>
      </div>

      <div>
        <label className="block text-text-secondary text-sm font-medium mb-2">
          Media Type
        </label>
        <select
          value={formData.media_type}
          onChange={(e) => setFormData({ ...formData, media_type: e.target.value })}
          className="w-full bg-surface-dark border border-border-dark rounded-lg px-4 py-2 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
        >
          <option value="File">File (Disk)</option>
          <option value="Tape">Tape</option>
        </select>
        <p className="text-text-secondary text-xs mt-1">Type of storage media</p>
      </div>

      <div>
        <label className="block text-text-secondary text-sm font-medium mb-2">
          Maximum Volume Size (GB)
        </label>
        <input
          type="number"
          value={formData.max_vol_bytes}
          onChange={(e) => setFormData({ ...formData, max_vol_bytes: e.target.value })}
          placeholder="e.g., 100"
          className="w-full bg-surface-dark border border-border-dark rounded-lg px-4 py-2 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
        />
        <p className="text-text-secondary text-xs mt-1">Maximum size in GB (optional, for disk volumes)</p>
      </div>

      <div>
        <label className="block text-text-secondary text-sm font-medium mb-2">
          Retention Period (Days)
        </label>
        <input
          type="number"
          value={formData.vol_retention}
          onChange={(e) => setFormData({ ...formData, vol_retention: e.target.value })}
          placeholder="e.g., 30"
          className="w-full bg-surface-dark border border-border-dark rounded-lg px-4 py-2 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
        />
        <p className="text-text-secondary text-xs mt-1">Number of days to retain the volume (optional)</p>
      </div>

      <div className="flex gap-3 justify-end pt-4 border-t border-border-dark">
        <button
          type="button"
          onClick={onCancel}
          className="px-4 py-2 rounded-lg bg-surface-dark border border-border-dark text-white text-sm font-bold hover:bg-[#2a3c50] transition-colors"
        >
          Cancel
        </button>
        <button
          type="submit"
          disabled={isLoading || !formData.volume_name || !formData.pool_name}
          className="px-4 py-2 rounded-lg bg-primary text-white text-sm font-bold hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {isLoading ? 'Creating...' : 'Create Volume'}
        </button>
      </div>
    </form>
  )
}

function UpdateVolumeForm({ volume, onSubmit, isLoading, onCancel }: { volume: StorageVolume; onSubmit: (data: any) => void; isLoading: boolean; onCancel: () => void }) {
  const [formData, setFormData] = useState({
    max_vol_bytes: volume.max_vol_bytes > 0 ? (volume.max_vol_bytes / (1024 * 1024 * 1024)).toString() : '',
    vol_retention: '',
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    onSubmit({
      max_vol_bytes: formData.max_vol_bytes ? parseInt(formData.max_vol_bytes) * 1024 * 1024 * 1024 : undefined,
      vol_retention: formData.vol_retention ? parseInt(formData.vol_retention) : undefined,
    })
  }

  return (
    <form onSubmit={handleSubmit} className="flex flex-col gap-4">
      <div>
        <label className="block text-text-secondary text-sm font-medium mb-2">
          Maximum Volume Size (GB)
        </label>
        <input
          type="number"
          value={formData.max_vol_bytes}
          onChange={(e) => setFormData({ ...formData, max_vol_bytes: e.target.value })}
          placeholder="e.g., 100"
          className="w-full bg-surface-dark border border-border-dark rounded-lg px-4 py-2 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
        />
        <p className="text-text-secondary text-xs mt-1">Current: {volume.max_vol_bytes > 0 ? `${(volume.max_vol_bytes / (1024 * 1024 * 1024)).toFixed(2)} GB` : 'Not set'}</p>
      </div>

      <div>
        <label className="block text-text-secondary text-sm font-medium mb-2">
          Retention Period (Days)
        </label>
        <input
          type="number"
          value={formData.vol_retention}
          onChange={(e) => setFormData({ ...formData, vol_retention: e.target.value })}
          placeholder="e.g., 30"
          className="w-full bg-surface-dark border border-border-dark rounded-lg px-4 py-2 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
        />
        <p className="text-text-secondary text-xs mt-1">Number of days to retain the volume</p>
      </div>

      <div className="flex gap-3 justify-end pt-4 border-t border-border-dark">
        <button
          type="button"
          onClick={onCancel}
          className="px-4 py-2 rounded-lg bg-surface-dark border border-border-dark text-white text-sm font-bold hover:bg-[#2a3c50] transition-colors"
        >
          Cancel
        </button>
        <button
          type="submit"
          disabled={isLoading || (!formData.max_vol_bytes && !formData.vol_retention)}
          className="px-4 py-2 rounded-lg bg-primary text-white text-sm font-bold hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {isLoading ? 'Updating...' : 'Update Volume'}
        </button>
      </div>
    </form>
  )
}

