import React, { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Link } from 'react-router-dom'
import { storageApi, Repository, zfsApi, ZFSPool, PhysicalDisk, ZFSDataset } from '@/api/storage'
import { formatBytes } from '@/lib/format'

// Component to render dataset rows for a pool
function DatasetRows({ poolId, onDeleteDataset, onCreateDataset }: { poolId: string; onDeleteDataset: (poolId: string, datasetName: string) => void; onCreateDataset: (poolId: string) => void }) {
  const queryKey = ['storage', 'zfs', 'pools', poolId, 'datasets']
  
  const { data: datasets = [], isLoading } = useQuery<ZFSDataset[]>({
    queryKey: queryKey,
    queryFn: () => zfsApi.listDatasets(poolId),
    refetchOnWindowFocus: true,
    refetchOnMount: true,
    staleTime: 0, // Always consider data stale to force refetch
    refetchInterval: 1000, // Auto-refresh every 1 second
  })

  if (isLoading) {
    return (
      <tr className="bg-[#151d26]">
        <td colSpan={7} className="py-3 px-5 pl-10 text-white/60 text-xs">
          Loading datasets...
        </td>
      </tr>
    )
  }

  if (datasets.length === 0) {
    return (
      <tr className="bg-[#151d26]">
        <td colSpan={7} className="py-3 px-5 pl-10">
          <div className="flex items-center justify-between">
            <span className="text-white/60 text-xs">No datasets found</span>
            <button
              onClick={(e) => {
                e.stopPropagation()
                onCreateDataset(poolId)
              }}
              className="px-3 py-1.5 bg-primary/20 hover:bg-primary/30 text-primary text-xs font-medium rounded-lg border border-primary/30 transition-colors flex items-center gap-1.5"
              title="Create Dataset"
            >
              <span className="material-symbols-outlined text-[16px]">add</span>
              Create Dataset
            </button>
          </div>
        </td>
      </tr>
    )
  }

  return (
    <>
      {datasets.map((dataset) => {
        const datasetUsagePercent = dataset.quota > 0 
          ? (dataset.used_bytes / dataset.quota) * 100 
          : dataset.available_bytes > 0 
            ? (dataset.used_bytes / (dataset.used_bytes + dataset.available_bytes)) * 100 
            : 0
        
        // Extract dataset name without pool prefix
        const datasetDisplayName = dataset.name.includes('/') 
          ? dataset.name.split('/').slice(1).join('/')
          : dataset.name

        return (
          <tr key={dataset.name} className="bg-[#151d26] hover:bg-[#1a242f] transition-colors">
            <td className="py-3 px-5"></td>
            <td className="py-3 px-5 pl-10">
              <div className="flex items-center gap-3 relative before:content-[''] before:absolute before:-left-4 before:top-1/2 before:-translate-y-1/2 before:w-3 before:h-px before:bg-border-dark before:opacity-50">
                <span className="material-symbols-outlined text-white/70 text-[18px]">
                  {dataset.type === 'volume' ? 'storage' : dataset.type === 'snapshot' ? 'camera' : 'folder'}
                </span>
                <div className="flex flex-col">
                  <span className="font-medium text-white">{datasetDisplayName}</span>
                  {dataset.mount_point && dataset.mount_point !== 'none' && dataset.mount_point !== '-' && (
                    <span className="text-xs text-white/50">{dataset.mount_point}</span>
                  )}
                  {dataset.type === 'volume' && (
                    <span className="text-xs text-primary/70">Volume (Block Device)</span>
                  )}
                </div>
              </div>
            </td>
            <td className="py-3 px-5">
              <span className={`inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-bold ${
                dataset.type === 'volume'
                  ? 'bg-blue-500/20 text-blue-400 border border-blue-500/30'
                  : dataset.mount_point && dataset.mount_point !== 'none' && dataset.mount_point !== '-'
                    ? 'bg-emerald-500/20 text-emerald-400 border border-emerald-500/30'
                    : 'bg-gray-500/20 text-gray-400 border border-gray-500/30'
              }`}>
                {dataset.type === 'volume' 
                  ? 'VOLUME' 
                  : dataset.mount_point && dataset.mount_point !== 'none' && dataset.mount_point !== '-'
                    ? 'MOUNTED' 
                    : 'UNMOUNTED'}
              </span>
            </td>
            <td className="py-3 px-5">
              <div className="flex flex-col gap-1 w-32">
                <div className="flex justify-between text-xs">
                  <span className="text-white font-medium">{formatBytes(dataset.used_bytes, 1)}</span>
                  <span className="text-white/80 font-medium">{formatBytes(dataset.available_bytes, 1)}</span>
                </div>
                <div className="w-full bg-[#233648] rounded-full h-1.5">
                  <div
                    className="h-1.5 rounded-full bg-primary"
                    style={{ width: `${Math.min(datasetUsagePercent, 100)}%` }}
                  ></div>
                </div>
              </div>
            </td>
            <td className="py-3 px-5 text-white/80 text-xs">
              {dataset.quota > 0 ? formatBytes(dataset.quota, 1) : 'Unlimited'}
            </td>
            <td className="py-3 px-5 text-white/80 text-xs">
              {dataset.compression.toUpperCase()}
            </td>
            <td className="py-3 px-5 text-right">
              <div className="flex items-center gap-1 justify-end">
                <button
                  onClick={(e) => {
                    e.stopPropagation()
                    if (confirm(`Are you sure you want to delete dataset "${datasetDisplayName}"? This action cannot be undone.`)) {
                      // Extract dataset name without pool prefix for API call
                      const datasetNameOnly = dataset.name.includes('/') 
                        ? dataset.name.split('/').slice(1).join('/')
                        : dataset.name
                      onDeleteDataset(poolId, datasetNameOnly)
                    }
                  }}
                  className="p-1 rounded-md hover:bg-red-500/20 text-red-400 hover:text-red-300 transition-colors"
                  title="Delete dataset"
                >
                  <span className="material-symbols-outlined text-[18px]">delete</span>
                </button>
              </div>
            </td>
          </tr>
        )
      })}
    </>
  )
}

export default function StoragePage() {
  const [expandedPools, setExpandedPools] = useState<Set<string>>(new Set())
  const [selectedPool, setSelectedPool] = useState<ZFSPool | null>(null)
  const [searchQuery, setSearchQuery] = useState('')
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [showAddSpareModal, setShowAddSpareModal] = useState(false)
  const [showCreateDatasetModal, setShowCreateDatasetModal] = useState(false)
  const [selectedPoolForDataset, setSelectedPoolForDataset] = useState<ZFSPool | null>(null)
  const [selectedSpareDisks, setSelectedSpareDisks] = useState<string[]>([])
  const [isRefreshingPools, setIsRefreshingPools] = useState(false)
  const [datasetForm, setDatasetForm] = useState({
    name: '',
    type: 'filesystem' as 'filesystem' | 'volume',
    compression: 'lz4',
    quota: '',
    reservation: '',
    mount_point: '',
  })
  const [createForm, setCreateForm] = useState({
    name: '',
    description: '',
    raid_level: 'stripe' as 'stripe' | 'mirror' | 'raidz' | 'raidz2' | 'raidz3',
    disks: [] as string[],
    compression: 'lz4',
    deduplication: false,
    auto_expand: false,
  })
  const queryClient = useQueryClient()

  const { data: disks = [], isLoading: disksLoading } = useQuery({
    queryKey: ['storage', 'disks'],
    queryFn: storageApi.listDisks,
  })

  const { data: repositories = [], isLoading: reposLoading } = useQuery({
    queryKey: ['storage', 'repositories'],
    queryFn: storageApi.listRepositories,
  })

  const { data: zfsPools = [], isLoading: poolsLoading } = useQuery({
    queryKey: ['storage', 'zfs', 'pools'],
    queryFn: zfsApi.listPools,
    refetchInterval: 3000, // Auto-refresh every 3 seconds
    staleTime: 0, // Always consider data stale
    refetchOnWindowFocus: true,
    refetchOnMount: true,
  })

  // Fetch ARC stats with auto-refresh every 2 seconds for live data
  const { data: arcStats } = useQuery({
    queryKey: ['storage', 'zfs', 'arc', 'stats'],
    queryFn: zfsApi.getARCStats,
    refetchInterval: 2000, // Refresh every 2 seconds for live data
    staleTime: 0,
  })


  const syncDisksMutation = useMutation({
    mutationFn: storageApi.syncDisks,
    onSuccess: async () => {
      // Invalidate and refetch disks
      await queryClient.invalidateQueries({ queryKey: ['storage', 'disks'] })
      // Refetch disks immediately
      queryClient.refetchQueries({ queryKey: ['storage', 'disks'] })
      alert('Disk rescan completed!')
    },
    onError: (error: any) => {
      console.error('Failed to rescan disks:', error)
      alert(error.response?.data?.error || 'Failed to rescan disks')
    },
  })

  const createPoolMutation = useMutation({
    mutationFn: zfsApi.createPool,
    onSuccess: async () => {
      // Invalidate and immediately refetch pools
      await queryClient.invalidateQueries({ queryKey: ['storage', 'zfs', 'pools'] })
      await queryClient.refetchQueries({ queryKey: ['storage', 'zfs', 'pools'] })
      await queryClient.invalidateQueries({ queryKey: ['storage', 'disks'] })
      setShowCreateModal(false)
      setCreateForm({
        name: '',
        description: '',
        raid_level: 'stripe',
        disks: [],
        compression: 'lz4',
        deduplication: false,
        auto_expand: false,
      })
      alert('Pool created successfully!')
    },
    onError: (error: any) => {
      console.error('Failed to create pool:', error)
      alert(error.response?.data?.error || 'Failed to create pool')
    },
  })

  const addSpareDiskMutation = useMutation({
    mutationFn: ({ poolId, disks }: { poolId: string; disks: string[] }) =>
      zfsApi.addSpareDisk(poolId, disks),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['storage', 'zfs', 'pools'] })
      queryClient.invalidateQueries({ queryKey: ['storage', 'disks'] })
      setShowAddSpareModal(false)
      setSelectedSpareDisks([])
      alert('Spare disks added successfully!')
    },
    onError: (error: any) => {
      console.error('Failed to add spare disks:', error)
      alert(error.response?.data?.error || 'Failed to add spare disks')
    },
  })

  const deletePoolMutation = useMutation({
    mutationFn: (poolId: string) => zfsApi.deletePool(poolId),
    onSuccess: async () => {
      // Invalidate and immediately refetch
      await queryClient.invalidateQueries({ queryKey: ['storage', 'zfs', 'pools'] })
      await queryClient.refetchQueries({ queryKey: ['storage', 'zfs', 'pools'] })
      await queryClient.invalidateQueries({ queryKey: ['storage', 'disks'] })
      setSelectedPool(null)
      alert('Pool destroyed successfully!')
    },
    onError: (error: any) => {
      console.error('Failed to delete pool:', error)
      alert(error.response?.data?.error || 'Failed to destroy pool')
    },
  })

  const createDatasetMutation = useMutation({
    mutationFn: ({ poolId, data }: { poolId: string; data: any }) =>
      zfsApi.createDataset(poolId, data),
    onSuccess: async (_, variables) => {
      // Ensure pool is expanded to show the new dataset
      setExpandedPools(prev => new Set(prev).add(variables.poolId))
      
      // Close modal and reset form
      setShowCreateDatasetModal(false)
      setSelectedPoolForDataset(null)
      setDatasetForm({
        name: '',
        type: 'filesystem',
        compression: 'lz4',
        quota: '',
        reservation: '',
        mount_point: '',
      })
      
      // Simply invalidate query - React Query will automatically refetch
      // Backend already saved to database, so next query will get fresh data
      queryClient.invalidateQueries({ 
        queryKey: ['storage', 'zfs', 'pools', variables.poolId, 'datasets'],
        exact: true
      })
      
      alert('Dataset created successfully!')
    },
    onError: (error: any) => {
      console.error('Failed to create dataset:', error)
      alert(error.response?.data?.error || 'Failed to create dataset')
    },
  })

  const deleteDatasetMutation = useMutation({
    mutationFn: ({ poolId, datasetName }: { poolId: string; datasetName: string }) =>
      zfsApi.deleteDataset(poolId, datasetName),
    onSuccess: async (_, variables) => {
      // Ensure pool is expanded to show updated list
      setExpandedPools(prev => new Set(prev).add(variables.poolId))
      
      // Simply invalidate and refetch - backend already removed from database
      await queryClient.invalidateQueries({ 
        queryKey: ['storage', 'zfs', 'pools', variables.poolId, 'datasets'],
        exact: true
      })
      
      alert('Dataset deleted successfully!')
    },
    onError: (error: any) => {
      console.error('Failed to delete dataset:', error)
      alert(error.response?.data?.error || 'Failed to delete dataset')
    },
  })

  const handleDeleteDataset = (poolId: string, datasetName: string) => {
    deleteDatasetMutation.mutate({ poolId, datasetName })
  }

  const handleCreateDataset = (poolId: string) => {
    const pool = zfsPools.find(p => p.id === poolId)
    if (pool) {
      setSelectedPoolForDataset(pool)
      setShowCreateDatasetModal(true)
    }
  }

  // Calculate stats - combine ZFS pools and LVM repositories
  const allPools: (ZFSPool | Repository)[] = [...zfsPools, ...repositories]
  const totalCapacity = allPools.reduce((sum, pool) => sum + (pool.size_bytes || 0), 0)
  const usedCapacity = allPools.reduce((sum, pool) => sum + (pool.used_bytes || 0), 0)
  const usagePercent = totalCapacity > 0 ? (usedCapacity / totalCapacity) * 100 : 0

  const healthyPools = allPools.filter((p) => {
    if ('health_status' in p) {
      const health = (p as ZFSPool).health_status?.toLowerCase() || ''
      return p.is_active && health === 'online'
    }
    return p.is_active
  }).length
  const degradedPools = allPools.filter((p) => {
    if ('health_status' in p) {
      const health = (p as ZFSPool).health_status?.toLowerCase() || ''
      return !p.is_active || health !== 'online'
    }
    return !p.is_active
  }).length
  const healthStatus = degradedPools === 0 ? 'Optimal' : 'Degraded'

  // Calculate efficiency ratio from ZFS pools
  // Efficiency = average compressratio across all active pools
  // Use actual compressratio from ZFS if available, otherwise estimate
  const activeZFSPools = zfsPools.filter(p => p.is_active && p.health_status?.toLowerCase() === 'online')
  const efficiencyRatio = activeZFSPools.length > 0
    ? activeZFSPools.reduce((sum, pool) => {
        // Use actual compressratio from ZFS if available
        if (pool.compress_ratio && pool.compress_ratio > 0) {
          // Deduplication can add additional savings (typically 1.2-2x)
          const dedupMultiplier = pool.deduplication ? 1.3 : 1.0
          return sum + (pool.compress_ratio * dedupMultiplier)
        }
        // Fallback: estimate based on compression type
        const compressionMultiplier: Record<string, number> = {
          'lz4': 1.5,
          'zstd': 2.5,
          'gzip': 2.0,
          'gzip-1': 1.8,
          'gzip-9': 2.5,
          'off': 1.0,
        }
        const baseRatio = compressionMultiplier[pool.compression?.toLowerCase() || 'lz4'] || 1.5
        const dedupMultiplier = pool.deduplication ? 1.3 : 1.0
        return sum + (baseRatio * dedupMultiplier)
      }, 0) / activeZFSPools.length
    : 1.0
  
  // Get compression and deduplication status from pools
  const hasCompression = activeZFSPools.some(p => p.compression && p.compression.toLowerCase() !== 'off')
  const hasDedup = activeZFSPools.some(p => p.deduplication)
  const compressionType = activeZFSPools.find(p => p.compression && p.compression.toLowerCase() !== 'off')?.compression?.toUpperCase() || 'LZ4'
  // Use live ARC stats if available, otherwise fallback to 0
  const arcHitRatio = arcStats?.hit_ratio ?? 0
  const arcCacheUsage = arcStats?.cache_usage ?? 0
  const arcCacheSize = arcStats?.cache_size ?? 0
  const arcCacheMax = arcStats?.cache_max ?? 0

  const togglePool = (poolId: string) => {
    const newExpanded = new Set(expandedPools)
    if (newExpanded.has(poolId)) {
      newExpanded.delete(poolId)
    } else {
      newExpanded.add(poolId)
    }
    setExpandedPools(newExpanded)
  }

  // Filter pools - prioritize ZFS pools, then LVM repositories
  const filteredPools = allPools.filter((pool) =>
    pool.name.toLowerCase().includes(searchQuery.toLowerCase())
  )

  return (
    <div className="flex flex-col h-full overflow-hidden bg-background-dark">
      {/* Header & Breadcrumbs */}
      <header className="flex-shrink-0 px-8 py-6 border-b border-border-dark bg-card-dark/50 backdrop-blur-sm z-10">
        <div className="max-w-[1400px] mx-auto w-full flex flex-col gap-4">
          {/* Breadcrumbs */}
          <nav className="flex items-center text-sm font-medium text-text-secondary">
            <Link to="/" className="hover:text-primary transition-colors">
              Home
            </Link>
            <span className="mx-2">/</span>
            <span className="text-white">Storage Management</span>
          </nav>
          <div className="flex flex-wrap items-end justify-between gap-4">
            <div className="flex flex-col gap-1">
              <h1 className="text-3xl font-extrabold text-white tracking-tight">Storage Pools</h1>
              <p className="text-text-secondary">Manage ZFS pools, datasets, and physical disks topology.</p>
            </div>
            <div className="flex items-center gap-3">
              <button
                onClick={() => syncDisksMutation.mutate()}
                disabled={syncDisksMutation.isPending}
                className="flex items-center gap-2 px-4 py-2 rounded-lg border border-border-dark bg-card-dark text-white text-sm font-bold hover:bg-[#233648] transition-colors disabled:opacity-50"
              >
                <span className={`material-symbols-outlined text-[20px] ${syncDisksMutation.isPending ? 'animate-spin' : ''}`}>
                  refresh
                </span>
                {syncDisksMutation.isPending ? 'Rescanning...' : 'Rescan Disks'}
              </button>
              <button
                onClick={async () => {
                  setIsRefreshingPools(true)
                  try {
                    await queryClient.invalidateQueries({ queryKey: ['storage', 'zfs', 'pools'] })
                    await queryClient.refetchQueries({ queryKey: ['storage', 'zfs', 'pools'] })
                    // Small delay to show feedback
                    await new Promise(resolve => setTimeout(resolve, 300))
                    alert('Pools refreshed successfully!')
                  } catch (error) {
                    console.error('Failed to refresh pools:', error)
                    alert('Failed to refresh pools. Please try again.')
                  } finally {
                    setIsRefreshingPools(false)
                  }
                }}
                disabled={poolsLoading || isRefreshingPools}
                className="flex items-center gap-2 px-4 py-2 rounded-lg border border-border-dark bg-card-dark text-white text-sm font-bold hover:bg-[#233648] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                title="Refresh pools list from database"
              >
                <span className={`material-symbols-outlined text-[20px] ${(poolsLoading || isRefreshingPools) ? 'animate-spin' : ''}`}>
                  sync
                </span>
                {(poolsLoading || isRefreshingPools) ? 'Refreshing...' : 'Refresh Pools'}
              </button>
              <button 
                onClick={() => setShowCreateModal(true)}
                className="relative flex items-center gap-2 px-4 py-2 rounded-lg border border-primary/30 bg-card-dark text-white text-sm font-bold hover:bg-[#233648] transition-all overflow-hidden electric-glow electric-glow-border"
              >
                {/* Electric glow gradient overlay */}
                <span className="absolute inset-0 bg-gradient-to-r from-primary/0 via-primary/15 to-primary/0 opacity-60"></span>
                {/* Shimmer effect */}
                <span className="absolute inset-0 bg-gradient-to-r from-transparent via-white/5 to-transparent animate-[shimmer_3s_infinite]"></span>
                <span className="relative flex items-center gap-2 z-10">
                  <span className="material-symbols-outlined text-[20px]">add_circle</span>
                  Create Pool
                </span>
              </button>
            </div>
          </div>
        </div>
      </header>

      {/* Scrollable Content */}
      <div className="flex-1 overflow-y-auto p-8 custom-scrollbar">
        <div className="max-w-[1400px] mx-auto w-full flex flex-col gap-8 pb-10">
          {/* Stats Overview */}
          <section className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            {/* Total Capacity */}
            <div className="bg-card-dark p-5 rounded-xl border border-border-dark shadow-sm">
              <div className="flex justify-between items-start mb-2">
                <p className="text-text-secondary text-sm font-semibold uppercase tracking-wider">Total Capacity</p>
                <span className="material-symbols-outlined text-text-secondary">database</span>
              </div>
              <div className="flex items-baseline gap-2">
                <h3 className="text-2xl font-bold text-white">{formatBytes(totalCapacity, 1)}</h3>
                <span className="text-xs text-text-secondary">Raw</span>
              </div>
              <div className="mt-3 w-full bg-[#233648] rounded-full h-1.5 overflow-hidden">
                <div className="bg-primary h-1.5 rounded-full" style={{ width: `${Math.min(usagePercent, 100)}%` }}></div>
              </div>
              <p className="mt-2 text-xs text-text-secondary">
                {usagePercent.toFixed(0)}% Used ({formatBytes(usedCapacity, 1)})
              </p>
            </div>

            {/* Health Status */}
            <div className="bg-card-dark p-5 rounded-xl border border-border-dark shadow-sm">
              <div className="flex justify-between items-start mb-2">
                <p className="text-white/70 text-sm font-semibold uppercase tracking-wider">Health Status</p>
                <span className={`material-symbols-outlined ${healthStatus === 'Optimal' ? 'text-emerald-500' : 'text-orange-500'}`}>
                  {healthStatus === 'Optimal' ? 'check_circle' : 'warning'}
                </span>
              </div>
              <div className="flex items-baseline gap-2">
                <h3 className={`text-2xl font-bold ${healthStatus === 'Optimal' ? 'text-emerald-500' : 'text-orange-500'}`}>
                  {healthStatus}
                </h3>
              </div>
              <p className="mt-2 text-xs text-white/80">
                {healthyPools} pool{healthyPools !== 1 ? 's' : ''} online
              </p>
              {healthStatus === 'Optimal' && (
                <p className="text-xs text-emerald-500 mt-1 font-medium">Last scrub: N/A</p>
              )}
            </div>

            {/* Efficiency */}
            <div className="bg-card-dark p-5 rounded-xl border border-border-dark shadow-sm">
              <div className="flex justify-between items-start mb-2">
                <p className="text-white/70 text-sm font-semibold uppercase tracking-wider">Efficiency</p>
                <span className="material-symbols-outlined text-white/70">compress</span>
              </div>
              <div className="flex items-baseline gap-2">
                <h3 className="text-2xl font-bold text-white">{efficiencyRatio}x</h3>
                <span className="text-xs text-white/70">Ratio</span>
              </div>
              <div className="flex gap-2 mt-3">
                {hasCompression && (
                  <span className="px-2 py-0.5 rounded bg-blue-500/10 text-blue-500 text-[10px] font-bold">
                    {compressionType}
                  </span>
                )}
                {hasDedup && (
                  <span className="px-2 py-0.5 rounded bg-purple-500/10 text-purple-500 text-[10px] font-bold">
                    DEDUP ON
                  </span>
                )}
                {!hasCompression && !hasDedup && (
                  <span className="px-2 py-0.5 rounded bg-gray-500/10 text-gray-500 text-[10px] font-bold">
                    NO COMPRESSION
                  </span>
                )}
              </div>
            </div>

            {/* Performance */}
            <div className="bg-card-dark p-5 rounded-xl border border-border-dark shadow-sm">
              <div className="flex justify-between items-start mb-2">
                <p className="text-white/70 text-sm font-semibold uppercase tracking-wider">ARC Hit Ratio</p>
                <span className="material-symbols-outlined text-white/70">memory</span>
              </div>
              <div className="flex items-baseline gap-2">
                <h3 className="text-2xl font-bold text-white">{arcHitRatio.toFixed(1)}%</h3>
              </div>
              <p className="mt-2 text-xs text-white/80">
                Cache Usage: {arcCacheMax > 0 ? `${formatBytes(arcCacheSize, 1)} / ${formatBytes(arcCacheMax, 1)} (${arcCacheUsage.toFixed(1)}%)` : 'N/A'}
              </p>
              <div className="mt-2 flex gap-1">
                <div className="h-1 flex-1 bg-emerald-500 rounded-full"></div>
                <div className="h-1 flex-1 bg-emerald-500 rounded-full"></div>
                <div className="h-1 flex-1 bg-emerald-500 rounded-full"></div>
                <div className="h-1 flex-1 bg-emerald-500/30 rounded-full"></div>
              </div>
            </div>
          </section>

          {/* Active Pools Table */}
          <section className="flex flex-col gap-4">
            <div className="flex items-center justify-between">
              <h2 className="text-xl font-bold text-white">Active Pools</h2>
              <div className="flex gap-2">
                <div className="relative">
                  <span className="material-symbols-outlined absolute left-2.5 top-1/2 -translate-y-1/2 text-white/70 text-[20px]">
                    search
                  </span>
                  <input
                    className="pl-10 pr-4 py-1.5 bg-[#233648] border border-border-dark rounded-lg text-sm text-white focus:ring-2 focus:ring-primary focus:border-transparent outline-none w-64 placeholder-white/50"
                    placeholder="Search datasets..."
                    type="text"
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                  />
                </div>
              </div>
            </div>
            <div className="bg-card-dark rounded-xl border border-border-dark overflow-hidden shadow-sm">
              <div className="overflow-x-auto">
                <table className="w-full text-left border-collapse">
                  <thead>
                    <tr className="bg-[#1e2832] border-b border-border-dark">
                      <th className="py-3 px-5 text-xs font-semibold uppercase tracking-wider text-white/70 w-10"></th>
                      <th className="py-3 px-5 text-xs font-semibold uppercase tracking-wider text-white/70">Name</th>
                      <th className="py-3 px-5 text-xs font-semibold uppercase tracking-wider text-white/70">Status</th>
                      <th className="py-3 px-5 text-xs font-semibold uppercase tracking-wider text-white/70">Used / Avail</th>
                      <th className="py-3 px-5 text-xs font-semibold uppercase tracking-wider text-white/70">Topology</th>
                      <th className="py-3 px-5 text-xs font-semibold uppercase tracking-wider text-white/70">Compression</th>
                      <th className="py-3 px-5 text-xs font-semibold uppercase tracking-wider text-white/70 text-right">Actions</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-border-dark text-sm">
                    {reposLoading || poolsLoading ? (
                      <tr>
                        <td colSpan={7} className="py-8 px-5 text-center text-white/80">
                          Loading pools...
                        </td>
                      </tr>
                    ) : filteredPools.length === 0 ? (
                      <tr>
                        <td colSpan={7} className="py-8 px-5 text-center text-white/80">
                          No pools found
                        </td>
                      </tr>
                    ) : (
                      filteredPools.map((pool) => {
                        const isExpanded = expandedPools.has(pool.id)
                        const poolUsagePercent = pool.size_bytes > 0 ? (pool.used_bytes / pool.size_bytes) * 100 : 0
                        const available = pool.size_bytes - pool.used_bytes
                        
                        // Check if it's a ZFS pool or LVM repository
                        const isZFSPool = 'raid_level' in pool
                        const healthStatus = isZFSPool ? ((pool as ZFSPool).health_status?.toLowerCase() || 'online') : 'online'
                        const isHealthy = pool.is_active && (healthStatus === 'online' || healthStatus === '')
                        
                        const statusColor = isHealthy
                          ? 'bg-emerald-500/20 text-emerald-400 border-emerald-500/30'
                          : 'bg-orange-500/20 text-orange-400 border-orange-500/30'

                        return (
                          <React.Fragment key={pool.id}>
                            {/* Parent Pool Row */}
                            <tr
                              className="group hover:bg-white/5 transition-colors cursor-pointer"
                              onClick={() => togglePool(pool.id)}
                            >
                              <td className="py-4 px-5">
                                <span
                                  className={`material-symbols-outlined text-[20px] text-white transition-transform ${
                                    isExpanded ? 'rotate-90' : ''
                                  }`}
                                >
                                  arrow_right
                                </span>
                              </td>
                              <td className="py-4 px-5">
                                <div className="flex items-center gap-3">
                                  <span
                                    className={`material-symbols-outlined ${
                                      isHealthy ? 'text-primary' : 'text-orange-500'
                                    }`}
                                  >
                                    {isHealthy ? 'dns' : 'warning'}
                                  </span>
                                  <div>
                                    <span className="font-bold text-white block">{pool.name}</span>
                                    <span className="text-xs text-white/70">
                                      {isZFSPool 
                                        ? `ZFS ${(pool as ZFSPool).raid_level.toUpperCase()}`
                                        : (pool as Repository).mount_point || 'Not mounted'}
                                    </span>
                                  </div>
                                </div>
                              </td>
                              <td className="py-4 px-5">
                                <span
                                  className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold border ${statusColor}`}
                                >
                                  <span
                                    className={`w-1.5 h-1.5 rounded-full ${
                                      isHealthy ? 'bg-emerald-500' : 'bg-orange-500 animate-pulse'
                                    }`}
                                  ></span>
                                  {isZFSPool ? healthStatus.toUpperCase() : (isHealthy ? 'ONLINE' : 'DEGRADED')}
                                </span>
                              </td>
                              <td className="py-4 px-5">
                                <div className="flex flex-col gap-1 w-32">
                                  <div className="flex justify-between text-xs">
                                    <span className="text-white font-medium">{formatBytes(pool.used_bytes, 1)}</span>
                                    <span className="text-white/80 font-medium">{formatBytes(available, 1)}</span>
                                  </div>
                                  <div className="w-full bg-[#233648] rounded-full h-1.5">
                                    <div
                                      className={`h-1.5 rounded-full ${
                                        isHealthy ? 'bg-primary' : 'bg-orange-500'
                                      }`}
                                      style={{ width: `${Math.min(poolUsagePercent, 100)}%` }}
                                    ></div>
                                  </div>
                                </div>
                              </td>
                              <td className="py-4 px-5 text-white">
                                {isZFSPool 
                                  ? `${(pool as ZFSPool).raid_level.toUpperCase()} (${(pool as ZFSPool).disks.length} disks)`
                                  : (pool as Repository).volume_group || 'N/A'}
                              </td>
                              <td className="py-4 px-5 text-white">
                                {isZFSPool 
                                  ? (pool as ZFSPool).compression.toUpperCase()
                                  : (pool as Repository).filesystem_type || 'LZ4'}
                              </td>
                              <td className="py-4 px-5 text-right">
                                <div className="flex items-center gap-1 justify-end">
                                  {isZFSPool && (
                                    <button
                                      className="p-1.5 rounded-md hover:bg-primary/20 text-primary hover:text-primary transition-colors"
                                      onClick={(e) => {
                                        e.stopPropagation()
                                        setSelectedPoolForDataset(pool as ZFSPool)
                                        setShowCreateDatasetModal(true)
                                      }}
                                      title="Create Dataset"
                                    >
                                      <span className="material-symbols-outlined text-[18px]">add</span>
                                    </button>
                                  )}
                                  <button
                                    className="p-1.5 rounded-md hover:bg-[#233648] text-white transition-colors"
                                    onClick={(e) => {
                                      e.stopPropagation()
                                      setSelectedPool(pool as ZFSPool)
                                    }}
                                  >
                                    <span className="material-symbols-outlined text-[20px]">more_vert</span>
                                  </button>
                                </div>
                              </td>
                            </tr>
                            {/* Child Datasets (if expanded) */}
                            {isExpanded && isZFSPool && (
                              <DatasetRows 
                                poolId={pool.id} 
                                onDeleteDataset={handleDeleteDataset} 
                                onCreateDataset={handleCreateDataset}
                              />
                            )}
                          </React.Fragment>
                        )
                      })
                    )}
                  </tbody>
                </table>
              </div>
              {/* Table Footer */}
              <div className="bg-[#1e2832] px-5 py-3 border-t border-border-dark flex justify-between items-center text-xs text-white/80">
                <span>Showing {filteredPools.length} active pool{filteredPools.length !== 1 ? 's' : ''}</span>
                <button className="hover:text-primary font-medium text-white/80">View Archived Pools</button>
              </div>
            </div>
          </section>

          {/* Physical Disks Grid */}
          <section className="flex flex-col gap-4">
            <div className="flex items-center justify-between">
              <h2 className="text-xl font-bold text-white">Physical Disks</h2>
              <button className="text-primary text-sm font-bold hover:underline">View All Disks</button>
            </div>
            {disksLoading ? (
              <div className="text-center py-8 text-white/80">Loading disks...</div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 xl:grid-cols-6 gap-4">
                {disks.map((disk) => {
                  const isHealthy = disk.health_status === 'healthy' || disk.health_status === 'online'
                  const isFaulted = disk.health_status === 'faulted' || disk.health_status === 'error'
                  const diskUsage = disk.is_used ? 66 : 0

                  return (
                    <div
                      key={disk.id}
                      className={`bg-card-dark rounded-lg p-4 border ${
                        isFaulted
                          ? 'border-red-500/30 bg-red-900/10 hover:border-red-500'
                          : 'border-border-dark hover:border-primary/50'
                      } flex flex-col gap-3 transition-colors group cursor-pointer relative overflow-hidden`}
                    >
                      <div className="absolute top-0 right-0 p-2">
                        <div
                          className={`w-2 h-2 rounded-full ${
                            isFaulted ? 'bg-red-500 animate-pulse' : isHealthy ? 'bg-emerald-500' : 'bg-blue-500'
                          }`}
                        ></div>
                      </div>
                      <div className="flex items-center gap-3">
                        <div
                          className={`w-10 h-10 rounded ${
                            isFaulted
                              ? 'bg-red-100 dark:bg-red-900/20'
                              : 'bg-[#233648]'
                          } flex items-center justify-center`}
                        >
                          <span
                            className={`material-symbols-outlined ${
                              isFaulted
                                ? 'text-red-500 group-hover:text-red-400'
                                : 'text-white/70 group-hover:text-primary'
                            } transition-colors`}
                          >
                            {isFaulted ? 'error' : 'hard_drive'}
                          </span>
                        </div>
                        <div className="flex flex-col">
                          <span className="text-sm font-bold text-white">{disk.device_path}</span>
                          <span className={`text-xs ${isFaulted ? 'text-red-500 font-bold' : 'text-white'}`}>
                            {isFaulted ? 'FAULTED' : `Slot ${disk.id.slice(-1)}`}
                          </span>
                        </div>
                      </div>
                        <div className="flex flex-col gap-1">
                        <div className="flex justify-between text-xs text-text-secondary">
                          <span>
                            {disk.vendor || 'Unknown'} {disk.model || ''}
                          </span>
                          <span>{formatBytes(disk.size_bytes, 1)}</span>
                        </div>
                        {disk.attached_to_pool && (
                          <div className="text-xs text-primary font-medium">
                            Attached to pool: {disk.attached_to_pool}
                          </div>
                        )}
                        <div className="flex gap-0.5 h-1.5 w-full rounded-full overflow-hidden bg-[#233648]">
                          <div
                            className={`${
                              isFaulted ? 'bg-red-500 opacity-50' : 'bg-primary'
                            }`}
                            style={{ width: `${diskUsage}%` }}
                          ></div>
                          <div className="bg-transparent flex-1"></div>
                        </div>
                        <div className="flex flex-col gap-0.5 mt-1">
                          <span className={`text-[10px] font-medium ${isFaulted ? 'text-red-400' : 'text-emerald-400'}`}>
                            {isFaulted ? 'FAULTED' : 'Healthy'}
                          </span>
                          <span className={`text-[10px] ${disk.is_used || disk.attached_to_pool ? 'text-primary' : 'text-white/60'}`}>
                            {disk.is_used || disk.attached_to_pool ? 'Provisioned' : 'Unprovisioned'}
                          </span>
                        </div>
                      </div>
                    </div>
                  )
                })}
              </div>
            )}
          </section>
        </div>
      </div>

      {/* Slide-over Panel (Properties) */}
      {selectedPool && (
        <>
          {/* Backdrop */}
          <div 
            className="fixed inset-0 bg-black/60 backdrop-blur-sm z-30"
            onClick={() => setSelectedPool(null)}
          />
          <div className="fixed inset-y-0 right-0 w-96 bg-card-dark border-l border-border-dark shadow-2xl z-40 flex flex-col">
          {/* Header */}
          <div className="flex items-center justify-between p-6 border-b border-border-dark bg-[#1e2832]">
            <h3 className="text-lg font-bold text-white">{selectedPool.name} Properties</h3>
            <button
              onClick={() => setSelectedPool(null)}
              className="text-white/80 hover:text-white transition-colors p-2 hover:bg-[#233648] rounded-lg"
            >
              <span className="material-symbols-outlined text-[24px]">close</span>
            </button>
          </div>
          {/* Content */}
          <div className="flex-1 overflow-y-auto p-6 flex flex-col gap-6 custom-scrollbar">
            {/* Quick Info */}
            <div className="p-4 rounded-lg bg-primary/10 border border-primary/20">
              <div className="flex items-center gap-3 mb-3">
                <span className="material-symbols-outlined text-primary text-[20px]">info</span>
                <span className="text-sm font-bold text-primary">
                  {selectedPool.is_active && selectedPool.health_status?.toLowerCase() === 'online' ? 'Healthy' : 'Degraded'}
                </span>
              </div>
              <p className="text-xs text-white/90 leading-relaxed mb-3">
                {selectedPool.is_active && selectedPool.health_status?.toLowerCase() === 'online'
                  ? 'This pool is operating normally.'
                  : 'This pool has issues and requires attention.'}
              </p>
              <div className="mt-3 space-y-1.5 text-xs">
                <p className="text-white/80">
                  RAID Level: <span className="font-bold text-white ml-1">{selectedPool.raid_level.toUpperCase()}</span>
                </p>
                <p className="text-white/80">
                  Data Disks: <span className="font-bold text-white ml-1">{selectedPool.disks.length}</span>
                  <span className="text-white/60 ml-1">({selectedPool.disks.join(', ')})</span>
                </p>
                {selectedPool.spare_disks && selectedPool.spare_disks.length > 0 && (
                  <p className="text-white/80">
                    Spare Disks: <span className="font-bold text-white ml-1">{selectedPool.spare_disks.length}</span>
                    <span className="text-white/60 ml-1">({selectedPool.spare_disks.join(', ')})</span>
                  </p>
                )}
              </div>
            </div>
            <div className="flex flex-col gap-4">
              {/* Setting */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-semibold text-white">Compression Level</label>
                <select 
                  defaultValue={selectedPool.compression}
                  className="w-full bg-[#233648] border border-border-dark rounded-lg px-3 py-2.5 text-sm text-white placeholder-white/50 focus:ring-2 focus:ring-primary focus:border-transparent outline-none"
                >
                  <option value="off">Off</option>
                  <option value="lz4">LZ4 (Recommended)</option>
                  <option value="zstd">ZSTD</option>
                  <option value="gzip">GZIP</option>
                </select>
                <p className="text-xs text-white/70 leading-relaxed">Balances performance and storage efficiency.</p>
              </div>
              {/* Setting */}
              <div className="flex flex-col gap-2 border-t border-border-dark pt-4">
                <div className="flex items-center justify-between">
                  <label className="text-sm font-semibold text-white">Deduplication</label>
                  <button 
                    className={`w-11 h-6 rounded-full relative transition-colors focus:outline-none focus:ring-2 focus:ring-primary ${
                      selectedPool.deduplication ? 'bg-primary' : 'bg-[#233648]'
                    }`}
                  >
                    <span
                      className={`absolute left-1 top-1 bg-white w-4 h-4 rounded-full transition-transform ${
                        selectedPool.deduplication ? 'transform translate-x-5' : 'transform translate-x-0'
                      }`}
                    ></span>
                  </button>
                </div>
                <p className="text-xs text-white/70 leading-relaxed">Requires significant RAM. Use with caution.</p>
              </div>
              {/* Setting */}
              <div className="flex flex-col gap-2 border-t border-border-dark pt-4">
                <div className="flex items-center justify-between">
                  <label className="text-sm font-semibold text-white">Auto-Expand</label>
                  <button 
                    className={`w-11 h-6 rounded-full relative transition-colors focus:outline-none focus:ring-2 focus:ring-primary ${
                      selectedPool.auto_expand ? 'bg-primary' : 'bg-[#233648]'
                    }`}
                  >
                    <span
                      className={`absolute left-1 top-1 bg-white w-4 h-4 rounded-full transition-transform ${
                        selectedPool.auto_expand ? 'transform translate-x-5' : 'transform translate-x-0'
                      }`}
                    ></span>
                  </button>
                </div>
                <p className="text-xs text-white/70 leading-relaxed">Automatically grow pool when larger disks are added.</p>
              </div>
              {/* Setting */}
              <div className="flex flex-col gap-2 border-t border-border-dark pt-4">
                <label className="text-sm font-semibold text-white">Scrub Interval</label>
                <div className="flex items-center gap-2">
                  <input
                    className="w-20 bg-[#233648] border border-border-dark rounded-lg px-3 py-2 text-sm text-white placeholder-white/50 focus:ring-2 focus:ring-primary focus:border-transparent outline-none"
                    type="number"
                    defaultValue={selectedPool.scrub_interval}
                  />
                  <span className="text-sm text-white/80 font-medium">days</span>
                </div>
                <p className="text-xs text-white/70 leading-relaxed">Data integrity check interval.</p>
              </div>

              {/* Add Spare Disk Section */}
              <div className="flex flex-col gap-2 border-t border-border-dark pt-4">
                <div className="flex items-center justify-between mb-2">
                  <label className="text-sm font-semibold text-white">Spare Disks</label>
                  <button
                    onClick={() => {
                      setShowAddSpareModal(true)
                      setSelectedSpareDisks([])
                    }}
                    className="px-3 py-1.5 text-xs font-bold text-primary border border-primary/30 rounded-lg hover:bg-primary/10 transition-colors flex items-center gap-1.5"
                  >
                    <span className="material-symbols-outlined text-[16px]">add</span>
                    Add Spare
                  </button>
                </div>
                <p className="text-xs text-white/70 leading-relaxed">
                  Spare disks are automatically used to replace failed disks in the pool.
                </p>
                {selectedPool.spare_disks && selectedPool.spare_disks.length > 0 && (
                  <div className="mt-2 space-y-1">
                    {selectedPool.spare_disks.map((spareDisk) => (
                      <div key={spareDisk} className="flex items-center gap-2 text-xs text-white/80 bg-[#233648] px-2 py-1 rounded">
                        <span className="material-symbols-outlined text-[14px] text-primary">hard_drive</span>
                        <span>{spareDisk}</span>
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          </div>
          {/* Footer Actions */}
          <div className="p-6 border-t border-border-dark bg-[#1e2832] flex gap-3">
            <button className="relative flex-1 px-4 py-2 rounded-lg border border-primary/30 bg-card-dark text-white text-sm font-bold hover:bg-[#233648] transition-all overflow-hidden electric-glow electric-glow-border">
              {/* Electric glow gradient overlay */}
              <span className="absolute inset-0 bg-gradient-to-r from-primary/0 via-primary/15 to-primary/0 opacity-60"></span>
              {/* Shimmer effect */}
              <span className="absolute inset-0 bg-gradient-to-r from-transparent via-white/5 to-transparent animate-[shimmer_3s_infinite]"></span>
              <span className="relative flex items-center justify-center gap-2 z-10">
                <span className="material-symbols-outlined text-[18px]">save</span>
                Save Changes
              </span>
            </button>
            <button
              onClick={() => setSelectedPool(null)}
              className="px-4 py-2 bg-card-dark border border-border-dark text-white text-sm font-bold rounded-lg hover:bg-[#233648] transition-colors"
            >
              Cancel
            </button>
          </div>
          <div className="p-6 pt-0 bg-[#1e2832]">
            <button
              onClick={() => {
                if (selectedPool && confirm(`Are you sure you want to destroy pool "${selectedPool.name}"? This action cannot be undone and will delete all data in the pool.`)) {
                  deletePoolMutation.mutate(selectedPool.id)
                }
              }}
              disabled={deletePoolMutation.isPending || !selectedPool}
              className="w-full px-4 py-2 border border-red-500/30 text-red-500 hover:bg-red-500/10 text-sm font-bold rounded-lg transition-colors flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <span className="material-symbols-outlined text-[18px]">
                {deletePoolMutation.isPending ? 'hourglass_empty' : 'delete'}
              </span>
              {deletePoolMutation.isPending ? 'Destroying...' : 'Export / Destroy Pool'}
            </button>
          </div>
        </div>
        </>
      )}

      {/* Create Pool Modal */}
      {showCreateModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
          <div className="bg-card-dark border border-border-dark rounded-xl shadow-2xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto custom-scrollbar">
            {/* Modal Header */}
            <div className="flex items-center justify-between p-6 border-b border-border-dark bg-[#1e2832]">
              <div>
                <h2 className="text-2xl font-bold text-white">Create ZFS Pool</h2>
                <p className="text-sm text-text-secondary mt-1">Create a new ZFS pool from available physical disks</p>
              </div>
              <button
                onClick={() => setShowCreateModal(false)}
                className="text-white/70 hover:text-white transition-colors p-2 hover:bg-[#233648] rounded-lg"
              >
                <span className="material-symbols-outlined text-[24px]">close</span>
              </button>
            </div>

            {/* Modal Content */}
            <form
              onSubmit={(e) => {
                e.preventDefault()
                if (!createForm.name || createForm.disks.length === 0) {
                  alert('Please fill in all required fields and select at least one disk')
                  return
                }
                // Validate RAID level requirements
                const minDisks: Record<string, number> = {
                  stripe: 1,
                  mirror: 2,
                  raidz: 3,
                  raidz2: 4,
                  raidz3: 5,
                }
                if (createForm.disks.length < minDisks[createForm.raid_level]) {
                  alert(`RAID level ${createForm.raid_level} requires at least ${minDisks[createForm.raid_level]} disk(s)`)
                  return
                }
                if (createForm.raid_level === 'mirror' && createForm.disks.length % 2 !== 0) {
                  alert('Mirror RAID requires an even number of disks')
                  return
                }
                createPoolMutation.mutate({
                  name: createForm.name,
                  description: createForm.description || undefined,
                  raid_level: createForm.raid_level,
                  disks: createForm.disks,
                  compression: createForm.compression,
                  deduplication: createForm.deduplication,
                  auto_expand: createForm.auto_expand,
                })
              }}
              className="p-6 space-y-6"
            >
              {/* Pool Name */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-white">
                  Pool Name <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  required
                  value={createForm.name}
                  onChange={(e) => setCreateForm({ ...createForm, name: e.target.value })}
                  className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2.5 text-sm text-white placeholder-white/50 focus:ring-2 focus:ring-primary focus:border-transparent outline-none"
                  placeholder="e.g., backup-pool-01"
                />
                <p className="text-xs text-white/70">Unique name for the ZFS pool</p>
              </div>

              {/* Description */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-white">Description</label>
                <textarea
                  value={createForm.description}
                  onChange={(e) => setCreateForm({ ...createForm, description: e.target.value })}
                  rows={2}
                  className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2.5 text-sm text-white placeholder-white/50 focus:ring-2 focus:ring-primary focus:border-transparent outline-none resize-none"
                  placeholder="Optional description for this pool"
                />
              </div>

              {/* RAID Level */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-white">
                  RAID Level <span className="text-red-500">*</span>
                </label>
                <select
                  required
                  value={createForm.raid_level}
                  onChange={(e) => setCreateForm({ ...createForm, raid_level: e.target.value as any, disks: [] })}
                  className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2.5 text-sm text-white focus:ring-2 focus:ring-primary focus:border-transparent outline-none"
                >
                  <option value="stripe">Stripe (No redundancy, 1+ disks)</option>
                  <option value="mirror">Mirror (2+ disks, even number)</option>
                  <option value="raidz">RAIDZ (3+ disks, single parity)</option>
                  <option value="raidz2">RAIDZ2 (4+ disks, double parity)</option>
                  <option value="raidz3">RAIDZ3 (5+ disks, triple parity)</option>
                </select>
                <p className="text-xs text-white/70">
                  {createForm.raid_level === 'stripe' && 'No redundancy, maximum capacity'}
                  {createForm.raid_level === 'mirror' && '50% capacity, full redundancy'}
                  {createForm.raid_level === 'raidz' && 'Single parity, good balance'}
                  {createForm.raid_level === 'raidz2' && 'Double parity, high reliability'}
                  {createForm.raid_level === 'raidz3' && 'Triple parity, maximum reliability'}
                </p>
              </div>

              {/* Disk Selection */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-white">
                  Select Disks <span className="text-red-500">*</span>
                </label>
                {disksLoading ? (
                  <div className="text-sm text-white/70">Loading disks...</div>
                ) : (
                  <div className="max-h-48 overflow-y-auto custom-scrollbar border border-border-dark rounded-lg bg-[#233648] p-3 space-y-2">
                    {disks.filter((d: PhysicalDisk) => !d.is_used).length === 0 ? (
                      <div className="text-sm text-orange-400 bg-orange-500/10 border border-orange-500/30 rounded-lg p-3">
                        No available disks. All disks are in use.
                      </div>
                    ) : (
                      disks
                        .filter((d: PhysicalDisk) => !d.is_used)
                        .map((disk: PhysicalDisk) => (
                          <label
                            key={disk.id}
                            className="flex items-center gap-3 p-2 rounded-lg hover:bg-[#1e2832] cursor-pointer transition-colors"
                          >
                            <input
                              type="checkbox"
                              checked={createForm.disks.includes(disk.device_path)}
                              onChange={(e) => {
                                if (e.target.checked) {
                                  setCreateForm({ ...createForm, disks: [...createForm.disks, disk.device_path] })
                                } else {
                                  setCreateForm({ ...createForm, disks: createForm.disks.filter((d) => d !== disk.device_path) })
                                }
                              }}
                              className="w-4 h-4 text-primary bg-[#233648] border-border-dark rounded focus:ring-primary"
                            />
                            <div className="flex-1">
                              <div className="text-sm font-medium text-white">{disk.device_path}</div>
                              <div className="text-xs text-white/70">
                                {disk.vendor || 'Unknown'} {disk.model || ''} • {formatBytes(disk.size_bytes, 1)}
                              </div>
                            </div>
                          </label>
                        ))
                    )}
                  </div>
                )}
                <p className="text-xs text-white/70">
                  Selected: {createForm.disks.length} disk(s). Minimum: {
                    createForm.raid_level === 'stripe' ? 1 :
                    createForm.raid_level === 'mirror' ? 2 :
                    createForm.raid_level === 'raidz' ? 3 :
                    createForm.raid_level === 'raidz2' ? 4 : 5
                  }
                </p>
              </div>

              {/* Compression */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-white">Compression</label>
                <select
                  value={createForm.compression}
                  onChange={(e) => setCreateForm({ ...createForm, compression: e.target.value })}
                  className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2.5 text-sm text-white focus:ring-2 focus:ring-primary focus:border-transparent outline-none"
                >
                  <option value="off">Off</option>
                  <option value="lz4">LZ4 (Recommended)</option>
                  <option value="zstd">ZSTD</option>
                  <option value="gzip">GZIP</option>
                </select>
                <p className="text-xs text-white/70">LZ4 provides good compression with minimal CPU overhead</p>
              </div>

              {/* Deduplication */}
              <div className="flex flex-col gap-2">
                <div className="flex items-center justify-between">
                  <label className="text-sm font-medium text-white">Deduplication</label>
                  <button
                    type="button"
                    onClick={() => setCreateForm({ ...createForm, deduplication: !createForm.deduplication })}
                    className={`w-11 h-6 rounded-full relative transition-colors focus:outline-none focus:ring-2 focus:ring-primary ${
                      createForm.deduplication ? 'bg-primary' : 'bg-[#233648]'
                    }`}
                  >
                    <span
                      className={`absolute left-1 top-1 bg-white w-4 h-4 rounded-full transition-transform ${
                        createForm.deduplication ? 'transform translate-x-5' : 'transform translate-x-0'
                      }`}
                    ></span>
                  </button>
                </div>
                <p className="text-xs text-white/70">Requires significant RAM. Use with caution.</p>
              </div>

              {/* Auto Expand */}
              <div className="flex flex-col gap-2">
                <div className="flex items-center justify-between">
                  <label className="text-sm font-medium text-white">Auto-Expand</label>
                  <button
                    type="button"
                    onClick={() => setCreateForm({ ...createForm, auto_expand: !createForm.auto_expand })}
                    className={`w-11 h-6 rounded-full relative transition-colors focus:outline-none focus:ring-2 focus:ring-primary ${
                      createForm.auto_expand ? 'bg-primary' : 'bg-[#233648]'
                    }`}
                  >
                    <span
                      className={`absolute left-1 top-1 bg-white w-4 h-4 rounded-full transition-transform ${
                        createForm.auto_expand ? 'transform translate-x-5' : 'transform translate-x-0'
                      }`}
                    ></span>
                  </button>
                </div>
                <p className="text-xs text-white/70">Automatically grow pool when larger disks are added</p>
              </div>

              {/* Form Actions */}
              <div className="flex items-center justify-end gap-3 pt-4 border-t border-border-dark">
                <button
                  type="button"
                  onClick={() => setShowCreateModal(false)}
                  className="flex items-center gap-2 px-4 py-2 rounded-lg border border-border-dark bg-card-dark text-white text-sm font-bold hover:bg-[#233648] transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={createPoolMutation.isPending || disks.filter((d: PhysicalDisk) => !d.is_used).length === 0 || createForm.disks.length === 0}
                  className="relative flex items-center gap-2 px-4 py-2 rounded-lg border border-primary/30 bg-card-dark text-white text-sm font-bold hover:bg-[#233648] transition-all overflow-hidden electric-glow electric-glow-border disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {/* Electric glow gradient overlay */}
                  <span className="absolute inset-0 bg-gradient-to-r from-primary/0 via-primary/15 to-primary/0 opacity-60"></span>
                  {/* Shimmer effect */}
                  <span className="absolute inset-0 bg-gradient-to-r from-transparent via-white/5 to-transparent animate-[shimmer_3s_infinite]"></span>
                  <span className="relative flex items-center gap-2 z-10">
                    {createPoolMutation.isPending ? (
                      <>
                        <span className="material-symbols-outlined text-[20px] animate-spin">refresh</span>
                        Creating...
                      </>
                    ) : (
                      <>
                        <span className="material-symbols-outlined text-[20px]">add_circle</span>
                        Create ZFS Pool
                      </>
                    )}
                  </span>
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Create Dataset Modal */}
      {showCreateDatasetModal && selectedPoolForDataset && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
          <div className="bg-card-dark border border-border-dark rounded-xl shadow-2xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto custom-scrollbar">
            {/* Modal Header */}
            <div className="flex items-center justify-between p-6 border-b border-border-dark bg-[#1e2832]">
              <div>
                <h2 className="text-2xl font-bold text-white">Create Dataset</h2>
                <p className="text-sm text-text-secondary mt-1">Create a new dataset in pool: {selectedPoolForDataset.name}</p>
              </div>
              <button
                onClick={() => {
                  setShowCreateDatasetModal(false)
                  setSelectedPoolForDataset(null)
                  setDatasetForm({
                    name: '',
                    type: 'filesystem',
                    compression: 'lz4',
                    quota: '',
                    reservation: '',
                    mount_point: '',
                  })
                }}
                className="text-white/70 hover:text-white transition-colors p-2 hover:bg-[#233648] rounded-lg"
              >
                <span className="material-symbols-outlined text-[24px]">close</span>
              </button>
            </div>

            {/* Modal Content */}
            <form
              onSubmit={(e) => {
                e.preventDefault()
                if (!datasetForm.name) {
                  alert('Please enter a dataset name')
                  return
                }
                if (datasetForm.type === 'volume' && (!datasetForm.quota || parseFloat(datasetForm.quota) <= 0)) {
                  alert('Volume size (quota) is required and must be greater than 0')
                  return
                }
                createDatasetMutation.mutate({
                  poolId: selectedPoolForDataset.id,
                  data: {
                    name: datasetForm.name,
                    type: datasetForm.type,
                    compression: datasetForm.compression || 'lz4',
                    quota: datasetForm.quota ? parseInt(datasetForm.quota) * 1024 * 1024 * 1024 : -1, // Convert GB to bytes
                    reservation: datasetForm.reservation ? parseInt(datasetForm.reservation) * 1024 * 1024 * 1024 : 0,
                    mount_point: datasetForm.mount_point || undefined,
                  },
                })
              }}
              className="p-6 space-y-6"
            >
              {/* Dataset Name */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-white">
                  Dataset Name <span className="text-red-500">*</span>
                </label>
                <input
                  type="text"
                  required
                  value={datasetForm.name}
                  onChange={(e) => setDatasetForm({ ...datasetForm, name: e.target.value })}
                  className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2.5 text-sm text-white placeholder-white/50 focus:ring-2 focus:ring-primary focus:border-transparent outline-none"
                  placeholder="e.g., backup-data"
                />
                <p className="text-xs text-white/70">Dataset will be created as: {selectedPoolForDataset.name}/{datasetForm.name || 'dataset-name'}</p>
              </div>

              {/* Dataset Type */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-white">
                  Type <span className="text-red-500">*</span>
                </label>
                <select
                  required
                  value={datasetForm.type}
                  onChange={(e) => setDatasetForm({ ...datasetForm, type: e.target.value as 'filesystem' | 'volume' })}
                  className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2.5 text-sm text-white focus:ring-2 focus:ring-primary focus:border-transparent outline-none"
                >
                  <option value="filesystem">Filesystem</option>
                  <option value="volume">Volume (Block Device)</option>
                </select>
                <p className="text-xs text-white/70">
                  {datasetForm.type === 'filesystem' 
                    ? 'A filesystem dataset that can be mounted and used like a directory'
                    : 'A volume that appears as a block device (like /dev/zvol/...)'}
                </p>
              </div>

              {/* Compression */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-white">Compression</label>
                <select
                  value={datasetForm.compression}
                  onChange={(e) => setDatasetForm({ ...datasetForm, compression: e.target.value })}
                  className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2.5 text-sm text-white focus:ring-2 focus:ring-primary focus:border-transparent outline-none"
                >
                  <option value="off">Off</option>
                  <option value="lz4">LZ4 (Recommended)</option>
                  <option value="zstd">ZSTD</option>
                  <option value="gzip">GZIP</option>
                </select>
                <p className="text-xs text-white/70">LZ4 provides good compression with minimal CPU overhead</p>
              </div>

              {/* Quota (Size for volumes, quota for filesystems) */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-white">
                  {datasetForm.type === 'volume' ? 'Volume Size (GB)' : 'Quota (GB)'} {datasetForm.type === 'volume' && <span className="text-red-500">*</span>}
                </label>
                <input
                  type="number"
                  required={datasetForm.type === 'volume'}
                  value={datasetForm.quota}
                  onChange={(e) => setDatasetForm({ ...datasetForm, quota: e.target.value })}
                  className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2.5 text-sm text-white placeholder-white/50 focus:ring-2 focus:ring-primary focus:border-transparent outline-none"
                  placeholder={datasetForm.type === 'volume' ? 'e.g., 100' : 'Leave empty for unlimited'}
                  min="1"
                />
                <p className="text-xs text-white/70">
                  {datasetForm.type === 'volume' 
                    ? 'Size of the volume in GB (required for volumes)'
                    : 'Maximum space this filesystem can use. Leave empty for unlimited.'}
                </p>
              </div>

              {/* Reservation */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-medium text-white">Reservation (GB)</label>
                <input
                  type="number"
                  value={datasetForm.reservation}
                  onChange={(e) => setDatasetForm({ ...datasetForm, reservation: e.target.value })}
                  className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2.5 text-sm text-white placeholder-white/50 focus:ring-2 focus:ring-primary focus:border-transparent outline-none"
                  placeholder="Leave empty for none"
                  min="0"
                />
                <p className="text-xs text-white/70">Guaranteed space reserved for this dataset</p>
              </div>

              {/* Mount Point - Only for filesystem datasets */}
              {datasetForm.type === 'filesystem' && (
                <div className="flex flex-col gap-2">
                  <label className="text-sm font-medium text-white">Mount Point</label>
                  <input
                    type="text"
                    value={datasetForm.mount_point}
                    onChange={(e) => setDatasetForm({ ...datasetForm, mount_point: e.target.value })}
                    className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2.5 text-sm text-white placeholder-white/50 focus:ring-2 focus:ring-primary focus:border-transparent outline-none"
                    placeholder="e.g., /mnt/backup-data (optional)"
                  />
                  <p className="text-xs text-white/70">Optional mount point. Leave empty for default location.</p>
                </div>
              )}

              {/* Form Actions */}
              <div className="flex items-center justify-end gap-3 pt-4 border-t border-border-dark">
                <button
                  type="button"
                  onClick={() => {
                    setShowCreateDatasetModal(false)
                    setSelectedPoolForDataset(null)
                    setDatasetForm({
                      name: '',
                      type: 'filesystem',
                      compression: 'lz4',
                      quota: '',
                      reservation: '',
                      mount_point: '',
                    })
                  }}
                  className="flex items-center gap-2 px-4 py-2 rounded-lg border border-border-dark bg-card-dark text-white text-sm font-bold hover:bg-[#233648] transition-colors"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  disabled={createDatasetMutation.isPending}
                  className="relative flex items-center gap-2 px-4 py-2 rounded-lg border border-primary/30 bg-card-dark text-white text-sm font-bold hover:bg-[#233648] transition-all overflow-hidden electric-glow electric-glow-border disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {/* Electric glow gradient overlay */}
                  <span className="absolute inset-0 bg-gradient-to-r from-primary/0 via-primary/15 to-primary/0 opacity-60"></span>
                  {/* Shimmer effect */}
                  <span className="absolute inset-0 bg-gradient-to-r from-transparent via-white/5 to-transparent animate-[shimmer_3s_infinite]"></span>
                  <span className="relative flex items-center gap-2 z-10">
                    {createDatasetMutation.isPending ? (
                      <>
                        <span className="material-symbols-outlined text-[18px] animate-spin">refresh</span>
                        Creating...
                      </>
                    ) : (
                      <>
                        <span className="material-symbols-outlined text-[18px]">add_circle</span>
                        Create Dataset
                      </>
                    )}
                  </span>
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* Add Spare Disk Modal */}
      {showAddSpareModal && selectedPool && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm">
          <div className="bg-card-dark border border-border-dark rounded-xl shadow-2xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto custom-scrollbar">
            {/* Modal Header */}
            <div className="flex items-center justify-between p-6 border-b border-border-dark bg-[#1e2832]">
              <div>
                <h2 className="text-2xl font-bold text-white">Add Spare Disks</h2>
                <p className="text-sm text-text-secondary mt-1">Add spare disks to pool: {selectedPool.name}</p>
              </div>
              <button
                onClick={() => {
                  setShowAddSpareModal(false)
                  setSelectedSpareDisks([])
                }}
                className="text-white/70 hover:text-white transition-colors p-2 hover:bg-[#233648] rounded-lg"
              >
                <span className="material-symbols-outlined text-[24px]">close</span>
              </button>
            </div>

            {/* Modal Content */}
            <div className="p-6 space-y-6">
              {/* Info Box */}
              <div className="p-4 rounded-lg bg-primary/10 border border-primary/20">
                <div className="flex items-center gap-3 mb-2">
                  <span className="material-symbols-outlined text-primary text-[20px]">info</span>
                  <span className="text-sm font-bold text-primary">About Spare Disks</span>
                </div>
                <p className="text-xs text-white/90 leading-relaxed">
                  Spare disks are automatically used to replace failed disks in the pool. They provide redundancy
                  and help maintain pool health without manual intervention.
                </p>
              </div>

              {/* Select Disks */}
              <div className="flex flex-col gap-2">
                <label className="text-sm font-semibold text-white">
                  Select Spare Disks <span className="text-red-500">*</span>
                </label>
                {disksLoading ? (
                  <div className="text-sm text-white/70">Loading disks...</div>
                ) : (disks.filter((d: PhysicalDisk) => !d.is_used).length === 0) ? (
                  <div className="text-sm text-orange-400 bg-orange-500/10 border border-orange-500/30 rounded-lg p-3">
                    No available disks found. Please ensure disks are connected and rescanned.
                  </div>
                ) : (
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 max-h-64 overflow-y-auto custom-scrollbar">
                    {disks.filter((d: PhysicalDisk) => !d.is_used).map((disk) => (
                      <div
                        key={disk.id}
                        className={`flex items-center justify-between p-3 rounded-lg border cursor-pointer transition-colors ${
                          selectedSpareDisks.includes(disk.device_path)
                            ? 'bg-primary/20 border-primary text-white'
                            : 'bg-[#233648] border-border-dark text-white/80 hover:bg-[#2a3e50]'
                        }`}
                        onClick={() => {
                          setSelectedSpareDisks((prev) =>
                            prev.includes(disk.device_path)
                              ? prev.filter((d) => d !== disk.device_path)
                              : [...prev, disk.device_path]
                          )
                        }}
                      >
                        <div className="flex items-center gap-2">
                          <input
                            type="checkbox"
                            checked={selectedSpareDisks.includes(disk.device_path)}
                            onChange={() => {
                              setSelectedSpareDisks((prev) =>
                                prev.includes(disk.device_path)
                                  ? prev.filter((d) => d !== disk.device_path)
                                  : [...prev, disk.device_path]
                              )
                            }}
                            className="form-checkbox h-4 w-4 text-primary rounded border-gray-300 focus:ring-primary bg-transparent"
                          />
                          <span className="text-sm font-medium">{disk.device_path}</span>
                        </div>
                        <span className="text-xs text-white/70">{formatBytes(disk.size_bytes, 1)}</span>
                      </div>
                    ))}
                  </div>
                )}
                <p className="text-xs text-white/70">
                  Selected: {selectedSpareDisks.length} disk(s)
                </p>
              </div>

              {/* Form Actions */}
              <div className="flex items-center justify-end gap-3 pt-4 border-t border-border-dark">
                <button
                  type="button"
                  onClick={() => {
                    setShowAddSpareModal(false)
                    setSelectedSpareDisks([])
                  }}
                  className="px-4 py-2 rounded-lg border border-border-dark bg-card-dark text-white text-sm font-bold hover:bg-[#233648] transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={() => {
                    if (selectedSpareDisks.length === 0) {
                      alert('Please select at least one disk')
                      return
                    }
                    addSpareDiskMutation.mutate({
                      poolId: selectedPool.id,
                      disks: selectedSpareDisks,
                    })
                  }}
                  disabled={addSpareDiskMutation.isPending || selectedSpareDisks.length === 0}
                  className="relative flex items-center gap-2 px-4 py-2 rounded-lg border border-primary/30 bg-card-dark text-white text-sm font-bold hover:bg-[#233648] transition-all overflow-hidden electric-glow electric-glow-border disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {/* Electric glow gradient overlay */}
                  <span className="absolute inset-0 bg-gradient-to-r from-primary/0 via-primary/15 to-primary/0 opacity-60"></span>
                  {/* Shimmer effect */}
                  <span className="absolute inset-0 bg-gradient-to-r from-transparent via-white/5 to-transparent animate-[shimmer_3s_infinite]"></span>
                  <span className="relative flex items-center gap-2 z-10">
                    {addSpareDiskMutation.isPending ? (
                      <span className="material-symbols-outlined text-[18px] animate-spin">refresh</span>
                    ) : (
                      <span className="material-symbols-outlined text-[18px]">add_circle</span>
                    )}
                    {addSpareDiskMutation.isPending ? 'Adding...' : 'Add Spare Disks'}
                  </span>
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
