import { useState, useEffect, useRef } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { scstAPI, type SCSTTarget, type SCSTInitiatorGroup, type SCSTPortal, type SCSTInitiator, type SCSTExtent, type CreateExtentRequest } from '@/api/scst'
import { Button } from '@/components/ui/button'
import { Plus, Settings, ChevronRight, Search, ChevronLeft, ChevronRight as ChevronRightIcon, CheckCircle, HardDrive, ArrowUpDown, ArrowUp, ChevronUp, ChevronDown, Copy, Network, X, Trash2, Save, RefreshCw, Terminal } from 'lucide-react'
import { Link } from 'react-router-dom'

export default function ISCSITargets() {
  const queryClient = useQueryClient()
  const [showCreateForm, setShowCreateForm] = useState(false)
  const [activeTab, setActiveTab] = useState('targets')
  const [expandedTarget, setExpandedTarget] = useState<string | null>(null)
  const [searchQuery, setSearchQuery] = useState('')

  const { data: targets, isLoading } = useQuery<SCSTTarget[]>({
    queryKey: ['scst-targets'],
    queryFn: scstAPI.listTargets,
    refetchInterval: 3000, // Auto-refresh every 3 seconds
    refetchIntervalInBackground: true, // Continue refetching even when tab is in background
    refetchOnWindowFocus: true, // Refetch when window regains focus
    refetchOnMount: true, // Always refetch on mount
    refetchOnReconnect: true, // Refetch when network reconnects
    staleTime: 0, // Consider data stale immediately to ensure fresh data
    gcTime: 0, // Don't cache data (formerly cacheTime)
    structuralSharing: false, // Disable structural sharing to ensure updates are detected
  })

  const applyConfigMutation = useMutation({
    mutationFn: scstAPI.applyConfig,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scst-targets'] })
      alert('Configuration applied successfully!')
    },
  })

  const filteredTargets = targets?.filter(target => 
    target.iqn.toLowerCase().includes(searchQuery.toLowerCase()) ||
    (target.alias && target.alias.toLowerCase().includes(searchQuery.toLowerCase()))
  ) || []

  return (
    <div className="flex-1 overflow-y-auto p-8">
      <div className="max-w-[1200px] mx-auto flex flex-col gap-6">
        {/* Breadcrumbs */}
        <div className="flex flex-wrap items-center gap-2">
          <Link to="/storage" className="text-text-secondary text-sm font-medium hover:text-white transition-colors">
            Storage
          </Link>
          <ChevronRight className="text-text-secondary" size={16} />
          <span className="text-white text-sm font-medium">iSCSI Management</span>
        </div>

        {/* Page Heading */}
        <div className="flex flex-wrap justify-between items-end gap-4">
          <div className="flex flex-col gap-2">
            <h1 className="text-white text-3xl font-extrabold leading-tight tracking-tight">iSCSI Management</h1>
            <p className="text-text-secondary text-base font-normal">Manage targets, portals, and initiator access control lists.</p>
          </div>
          <div className="flex items-center gap-3">
            <Button
              variant="outline"
              onClick={() => applyConfigMutation.mutate()}
              disabled={applyConfigMutation.isPending}
              className="flex items-center gap-2 px-4 h-10 rounded-lg bg-card-dark border border-border-dark hover:bg-white/5 text-white text-sm font-semibold"
            >
              <Settings size={20} />
              <span>Global Settings</span>
            </Button>
            <Button
              onClick={() => setShowCreateForm(true)}
              className="flex items-center gap-2 px-4 h-10 rounded-lg bg-primary hover:bg-blue-600 text-white text-sm font-bold shadow-lg shadow-blue-900/20"
            >
              <Plus size={20} />
              <span>Create Target</span>
            </Button>
          </div>
        </div>

        {/* Stats Cards */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="flex flex-col gap-1 rounded-xl p-5 bg-card-dark border border-border-dark shadow-sm">
            <div className="flex items-center justify-between mb-2">
              <p className="text-text-secondary text-sm font-medium uppercase tracking-wider">Service Status</p>
              <CheckCircle className="text-green-500" size={24} />
            </div>
            <p className="text-white text-2xl font-bold">Running</p>
            <p className="text-green-500 text-xs font-medium mt-1">Uptime: 14d 2h</p>
          </div>
          <div className="flex flex-col gap-1 rounded-xl p-5 bg-card-dark border border-border-dark shadow-sm">
            <div className="flex items-center justify-between mb-2">
              <p className="text-text-secondary text-sm font-medium uppercase tracking-wider">Port Binding</p>
              <Network className="text-text-secondary" size={24} />
            </div>
            <p className="text-white text-2xl font-bold">3260</p>
            <p className="text-text-secondary text-xs font-medium mt-1">Listening on 0.0.0.0</p>
          </div>
          <div className="flex flex-col gap-1 rounded-xl p-5 bg-card-dark border border-border-dark shadow-sm">
            <div className="flex items-center justify-between mb-2">
              <p className="text-text-secondary text-sm font-medium uppercase tracking-wider">Active Sessions</p>
              <ArrowUpDown className="text-primary" size={24} />
            </div>
            <div className="flex items-baseline gap-2">
              <p className="text-white text-2xl font-bold">12</p>
              <span className="text-green-500 text-sm font-medium flex items-center">
                <ArrowUp size={16} /> 2
              </span>
            </div>
            <p className="text-text-secondary text-xs font-medium mt-1">Total throughput: 450 MB/s</p>
          </div>
        </div>

        {/* Tabs & Filters */}
        <div className="flex flex-col bg-card-dark border border-border-dark rounded-xl overflow-hidden shadow-sm">
          {/* Tabs Header */}
          <div className="border-b border-border-dark px-6">
            <div className="flex gap-8">
              <button
                onClick={() => setActiveTab('targets')}
                className={`relative py-4 text-sm tracking-wide transition-colors ${
                  activeTab === 'targets'
                    ? 'text-primary font-bold'
                    : 'text-text-secondary hover:text-white font-medium'
                }`}
              >
                Targets
                {activeTab === 'targets' && (
                  <div className="absolute bottom-0 left-0 w-full h-0.5 bg-primary rounded-t-full"></div>
                )}
              </button>
              <button
                onClick={() => setActiveTab('portals')}
                className={`relative py-4 text-sm tracking-wide transition-colors ${
                  activeTab === 'portals'
                    ? 'text-primary font-bold'
                    : 'text-text-secondary hover:text-white font-medium'
                }`}
              >
                Portals
                {activeTab === 'portals' && (
                  <div className="absolute bottom-0 left-0 w-full h-0.5 bg-primary rounded-t-full"></div>
                )}
              </button>
              <button
                onClick={() => setActiveTab('initiators')}
                className={`relative py-4 text-sm tracking-wide transition-colors ${
                  activeTab === 'initiators'
                    ? 'text-primary font-bold'
                    : 'text-text-secondary hover:text-white font-medium'
                }`}
              >
                Initiators
                {activeTab === 'initiators' && (
                  <div className="absolute bottom-0 left-0 w-full h-0.5 bg-primary rounded-t-full"></div>
                )}
              </button>
              <button
                onClick={() => setActiveTab('extents')}
                className={`relative py-4 text-sm tracking-wide transition-colors ${
                  activeTab === 'extents'
                    ? 'text-primary font-bold'
                    : 'text-text-secondary hover:text-white font-medium'
                }`}
              >
                Extents
                {activeTab === 'extents' && (
                  <div className="absolute bottom-0 left-0 w-full h-0.5 bg-primary rounded-t-full"></div>
                )}
              </button>
              <button
                onClick={() => setActiveTab('groups')}
                className={`relative py-4 text-sm tracking-wide transition-colors ${
                  activeTab === 'groups'
                    ? 'text-primary font-bold'
                    : 'text-text-secondary hover:text-white font-medium'
                }`}
              >
                Groups
                {activeTab === 'groups' && (
                  <div className="absolute bottom-0 left-0 w-full h-0.5 bg-primary rounded-t-full"></div>
                )}
              </button>
              <button
                onClick={() => setActiveTab('config')}
                className={`relative py-4 text-sm tracking-wide transition-colors ${
                  activeTab === 'config'
                    ? 'text-primary font-bold'
                    : 'text-text-secondary hover:text-white font-medium'
                }`}
              >
                Config Editor
                {activeTab === 'config' && (
                  <div className="absolute bottom-0 left-0 w-full h-0.5 bg-primary rounded-t-full"></div>
                )}
              </button>
            </div>
          </div>

          {/* Toolbar */}
          <div className="p-4 flex items-center justify-between gap-4 border-b border-border-dark/50 bg-[#141d26]">
            <div className="relative flex-1 max-w-md">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-text-secondary" size={20} />
              <input
                type="text"
                placeholder="Search targets by alias or IQN..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full bg-[#0f161d] border border-border-dark rounded-lg pl-10 pr-4 py-2 text-sm text-white focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all placeholder-text-secondary/50"
              />
            </div>
            <div className="flex items-center gap-3">
              <div className="flex items-center gap-2 px-3 py-1.5 rounded-md bg-[#0f161d] border border-border-dark">
                <span className="text-xs text-text-secondary font-medium">Filter:</span>
                <select 
                  className="bg-[#0f161d] text-xs text-white font-medium focus:outline-none cursor-pointer border-none appearance-none pr-6"
                  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='%23999' d='M6 9L1 4h10z'/%3E%3C/svg%3E")`,
                    backgroundRepeat: 'no-repeat',
                    backgroundPosition: 'right 0 center',
                    paddingRight: '24px'
                  }}
                >
                  <option className="bg-[#0f161d] text-white">All Status</option>
                  <option className="bg-[#0f161d] text-white">Online</option>
                  <option className="bg-[#0f161d] text-white">Offline</option>
                </select>
              </div>
            </div>
          </div>

          {/* Targets List */}
          {activeTab === 'targets' && (
            <div className="flex flex-col">
              {isLoading ? (
                <div className="p-8 text-center text-text-secondary">Loading targets...</div>
              ) : filteredTargets.length > 0 ? (
                <>
                  {filteredTargets.map((target, index) => (
                    <TargetRow
                      key={target.id}
                      target={target}
                      isExpanded={expandedTarget === target.id}
                      onToggle={() => setExpandedTarget(expandedTarget === target.id ? null : target.id)}
                      onDelete={() => {
                        // Close expanded view if this target was expanded
                        if (expandedTarget === target.id) {
                          setExpandedTarget(null)
                        }
                      }}
                      isLast={index === filteredTargets.length - 1}
                    />
                  ))}
                </>
              ) : (
                <div className="p-12 text-center">
                  <p className="text-text-secondary">No targets found</p>
                </div>
              )}

              {/* Pagination */}
              <div className="p-4 bg-[#141d26] border-t border-border-dark flex items-center justify-between">
                <p className="text-xs text-text-secondary">
                  Showing 1-{filteredTargets.length} of {filteredTargets.length} targets
                </p>
                <div className="flex gap-2">
                  <button className="p-1 rounded text-text-secondary hover:text-white hover:bg-white/10 disabled:opacity-50">
                    <ChevronLeft size={20} />
                  </button>
                  <button className="p-1 rounded text-text-secondary hover:text-white hover:bg-white/10">
                    <ChevronRightIcon size={20} />
                  </button>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'portals' && (
            <PortalsTab />
          )}

          {activeTab === 'initiators' && (
            <InitiatorsTab />
          )}

          {activeTab === 'extents' && (
            <ExtentsTab />
          )}

          {activeTab === 'groups' && (
            <InitiatorGroupsTab />
          )}

          {activeTab === 'config' && (
            <ConfigEditorTab />
          )}
        </div>
      </div>

      {/* Create Target Form Modal */}
      {showCreateForm && (
        <CreateTargetForm
          onClose={() => setShowCreateForm(false)}
          onSuccess={async () => {
            setShowCreateForm(false)
            // Force refetch targets list to ensure fresh data
            await queryClient.invalidateQueries({ queryKey: ['scst-targets'] })
            await queryClient.refetchQueries({ queryKey: ['scst-targets'] })
          }}
        />
      )}
    </div>
  )
}

interface TargetRowProps {
  target: SCSTTarget
  isExpanded: boolean
  onToggle: () => void
  onDelete?: () => void
  isLast?: boolean
}

function TargetRow({ target, isExpanded, onToggle, onDelete }: TargetRowProps) {
  // Fetch LUNs when expanded
  const { data: targetData } = useQuery({
    queryKey: ['scst-target', target.id],
    queryFn: () => scstAPI.getTarget(target.id),
    enabled: isExpanded, // Only fetch when expanded
  })

  const luns = targetData?.luns || []
  const initiatorGroups = targetData?.initiator_groups || []
  const [showEditPolicy, setShowEditPolicy] = useState(false)
  const queryClient = useQueryClient()
  const statusColor = target.is_active
    ? 'bg-green-500/20 text-green-400 border-green-500/20'
    : 'bg-red-500/20 text-red-400 border-red-500/20'
  const statusText = target.is_active ? 'Online' : 'Offline'

  const enableMutation = useMutation({
    mutationFn: () => scstAPI.enableTarget(target.id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scst-targets'] })
      queryClient.invalidateQueries({ queryKey: ['scst-target', target.id] })
    },
  })

  const disableMutation = useMutation({
    mutationFn: () => scstAPI.disableTarget(target.id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scst-targets'] })
      queryClient.invalidateQueries({ queryKey: ['scst-target', target.id] })
    },
  })

  const deleteMutation = useMutation({
    mutationFn: () => scstAPI.deleteTarget(target.id),
    onSuccess: async () => {
      // Close expanded view if this target was expanded
      if (isExpanded) {
        onToggle()
      }
      // Call onDelete callback if provided
      if (onDelete) {
        onDelete()
      }
      
      // Optimistically remove target from cache immediately
      queryClient.setQueryData<SCSTTarget[]>(['scst-targets'], (oldData) => {
        if (!oldData) return oldData
        return oldData.filter(t => t.id !== target.id)
      })
      
      // Remove target-specific queries from cache
      queryClient.removeQueries({ queryKey: ['scst-target', target.id] })
      
      // Invalidate and refetch targets list to ensure consistency
      await queryClient.invalidateQueries({ queryKey: ['scst-targets'] })
      await queryClient.refetchQueries({ 
        queryKey: ['scst-targets'],
        type: 'active' // Only refetch active queries
      })
    },
    onError: (error: any) => {
      // On error, refetch to restore correct state
      queryClient.refetchQueries({ queryKey: ['scst-targets'] })
      alert(`Failed to delete target: ${error.response?.data?.error || error.message}`)
    },
  })

  const removeLUNMutation = useMutation({
    mutationFn: ({ targetId, lunId }: { targetId: string; lunId: string }) => 
      scstAPI.removeLUN(targetId, lunId),
    onMutate: async ({ lunId }) => {
      // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
      await queryClient.cancelQueries({ queryKey: ['scst-target', target.id] })
      await queryClient.cancelQueries({ queryKey: ['scst-targets'] })

      // Snapshot the previous value
      const previousTarget = queryClient.getQueryData(['scst-target', target.id])
      const previousTargets = queryClient.getQueryData<SCSTTarget[]>(['scst-targets'])

      // Optimistically update to remove the LUN from target
      queryClient.setQueryData(['scst-target', target.id], (old: any) => {
        if (!old) return old
        return {
          ...old,
          luns: old.luns ? old.luns.filter((lun: any) => lun.id !== lunId) : []
        }
      })

      // Optimistically update LUN count in targets list
      queryClient.setQueryData<SCSTTarget[]>(['scst-targets'], (old) => {
        if (!old) return old
        return old.map(t => 
          t.id === target.id 
            ? { ...t, lun_count: Math.max(0, (t.lun_count || 0) - 1) }
            : t
        )
      })

      return { previousTarget, previousTargets }
    },
    onSuccess: async () => {
      // Remove target-specific queries from cache
      queryClient.removeQueries({ queryKey: ['scst-target', target.id] })
      
      // Invalidate and refetch queries to update UI
      await queryClient.invalidateQueries({ queryKey: ['scst-targets'] })
      await queryClient.invalidateQueries({ queryKey: ['scst-target', target.id] })
      
      // Explicitly refetch the target data if the target is expanded
      if (isExpanded) {
        await queryClient.refetchQueries({ queryKey: ['scst-target', target.id] })
      }
      
      // Refetch targets list to update LUN count
      await queryClient.refetchQueries({ 
        queryKey: ['scst-targets'],
        type: 'active'
      })
    },
    onError: (error: any, _variables, context) => {
      // If 404, treat as success (LUN already deleted)
      if (error.response?.status === 404) {
        // LUN already deleted, just refresh to sync UI
        queryClient.invalidateQueries({ queryKey: ['scst-target', target.id] })
        queryClient.invalidateQueries({ queryKey: ['scst-targets'] })
        queryClient.refetchQueries({ queryKey: ['scst-target', target.id] })
        queryClient.refetchQueries({ queryKey: ['scst-targets'] })
        return
      }
      
      // Rollback optimistic update
      if (context?.previousTarget) {
        queryClient.setQueryData(['scst-target', target.id], context.previousTarget)
      }
      if (context?.previousTargets) {
        queryClient.setQueryData<SCSTTarget[]>(['scst-targets'], context.previousTargets)
      }
      
      // On error, refetch to restore correct state
      queryClient.refetchQueries({ queryKey: ['scst-target', target.id] })
      queryClient.refetchQueries({ queryKey: ['scst-targets'] })
      alert(`Failed to remove LUN: ${error.response?.data?.error || error.message}`)
    },
  })

  return (
    <div className={`group border-b border-border-dark ${isExpanded ? 'bg-white/[0.02]' : 'bg-transparent'}`}>
      {/* Main Row */}
      <div
        className={`flex items-center p-4 gap-4 hover:bg-white/5 transition-colors cursor-pointer border-l-4 ${
          isExpanded ? 'border-primary' : 'border-transparent hover:border-border-dark'
        }`}
        onClick={onToggle}
      >
        <div className={`p-2 rounded-md ${isExpanded ? 'bg-primary/10 text-primary' : 'bg-border-dark/50 text-text-secondary'}`}>
          <Network size={24} />
        </div>
        <div className="flex-1 min-w-0 flex flex-col gap-1">
          <div className="flex items-center gap-3">
            <span className="text-white font-bold text-sm">{target.alias || target.iqn.split(':').pop()}</span>
            <span className={`px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wide border ${statusColor}`}>
              {statusText}
            </span>
            {target.is_active ? (
              <button
                onClick={(e) => {
                  e.stopPropagation()
                  if (confirm('Disable this target? It will stop accepting iSCSI connections.')) {
                    disableMutation.mutate()
                  }
                }}
                className="px-2 py-1 text-xs bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded border border-red-500/20"
                title="Disable target"
              >
                Disable
              </button>
            ) : (
              <button
                onClick={(e) => {
                  e.stopPropagation()
                  enableMutation.mutate()
                }}
                className="px-2 py-1 text-xs bg-green-500/20 text-green-400 hover:bg-green-500/30 rounded border border-green-500/20"
                title="Enable target"
              >
                Enable
              </button>
            )}
          </div>
          <div className="flex items-center gap-2 group/iqn">
            <span className="text-text-secondary font-mono text-xs truncate">{target.iqn}</span>
            <button
              className="opacity-0 group-hover/iqn:opacity-100 text-text-secondary hover:text-white transition-opacity"
              title="Copy IQN"
              onClick={(e) => {
                e.stopPropagation()
                navigator.clipboard.writeText(target.iqn)
              }}
            >
              <Copy size={14} />
            </button>
          </div>
        </div>
        <div className="hidden md:flex items-center gap-8 mr-4">
          <div className="flex flex-col items-end">
            <span className="text-[10px] uppercase text-text-secondary font-bold tracking-wider">LUNs</span>
            <div className="flex items-center gap-1">
              <HardDrive className="text-text-secondary" size={16} />
              <span className="text-white text-sm font-bold">{target.lun_count || 0}</span>
            </div>
          </div>
          <div className="flex flex-col items-end">
            <span className="text-[10px] uppercase text-text-secondary font-bold tracking-wider">Auth</span>
            <span className="text-white text-sm font-medium">None</span>
          </div>
        </div>
        <button
          className="p-2 hover:bg-white/10 rounded-full text-text-secondary hover:text-white transition-colors"
          onClick={(e) => {
            e.stopPropagation()
            onToggle()
          }}
        >
          {isExpanded ? <ChevronUp size={24} /> : <ChevronDown size={24} />}
        </button>
      </div>

      {/* Expanded Detail Panel */}
      {isExpanded && (
        <div className="px-4 pb-4 pt-0">
          <div className="bg-[#0f161d] border border-border-dark rounded-lg p-4 grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* Left: LUNs */}
            <div className="flex flex-col gap-3">
              <div className="flex items-center justify-between">
                <h4 className="text-xs font-bold text-text-secondary uppercase tracking-wider">Attached LUNs</h4>
                <Link
                  to={`/iscsi/${target.id}`}
                  className="text-primary text-xs font-bold hover:underline"
                  onClick={(e) => e.stopPropagation()}
                >
                  + Add LUN
                </Link>
              </div>
              <div className="flex flex-col gap-2">
                {luns.length > 0 ? (
                  luns.map((lun) => (
                    <div
                      key={lun.id}
                      className="p-3 rounded bg-card-dark border border-border-dark flex items-center justify-between"
                    >
                      <div className="flex flex-col gap-1">
                        <div className="flex items-center gap-2">
                          <span className="text-white text-sm font-medium">LUN {lun.lun_number}</span>
                          {lun.is_active && (
                            <span className="px-2 py-0.5 text-xs font-medium rounded bg-green-100 text-green-800">
                              Active
                            </span>
                          )}
                        </div>
                        <div className="text-text-secondary text-xs">
                          {lun.handler || 'Unknown'} • {lun.device_path || 'No path'}
                        </div>
                        <div className="text-text-secondary text-xs">
                          {lun.device_type || 'Unknown type'}
                        </div>
                      </div>
                      <button
                        onClick={() => {
                          if (confirm(`Remove LUN ${lun.lun_number} from this target?`)) {
                            removeLUNMutation.mutate({ targetId: target.id, lunId: lun.id })
                          }
                        }}
                        disabled={removeLUNMutation.isPending}
                        className="p-1.5 hover:bg-red-500/10 rounded text-text-secondary hover:text-red-400 transition-colors disabled:opacity-50"
                        title="Remove LUN"
                      >
                        <Trash2 size={14} />
                      </button>
                    </div>
                  ))
                ) : (
                  <div className="p-3 rounded bg-card-dark border border-border-dark text-center text-text-secondary text-sm">
                    No LUNs attached
                  </div>
                )}
              </div>
            </div>

            {/* Right: ACLs & Config */}
            <div className="flex flex-col gap-3">
              <div className="flex items-center justify-between">
                <h4 className="text-xs font-bold text-text-secondary uppercase tracking-wider">Access Control</h4>
                <button 
                  className="text-primary text-xs font-bold hover:underline"
                  onClick={(e) => {
                    e.stopPropagation()
                    setShowEditPolicy(true)
                  }}
                >
                  Edit Policy
                </button>
                <button
                  onClick={(e) => {
                    e.stopPropagation()
                    if (confirm(`Delete target "${target.alias || target.iqn}"? This will remove the target from SCST and all associated LUNs and initiators. This action cannot be undone.`)) {
                      deleteMutation.mutate()
                    }
                  }}
                  disabled={deleteMutation.isPending}
                  className="px-3 py-1.5 text-xs bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded border border-red-500/20 disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
                >
                  <Trash2 size={14} />
                  Delete Target
                </button>
              </div>
              <div className="flex flex-col gap-2 h-full">
                <div className="p-3 rounded bg-card-dark border border-border-dark flex flex-col gap-2">
                  <div className="flex justify-between items-center pb-2 border-b border-border-dark/50">
                    <span className="text-text-secondary text-xs">Auth Method</span>
                    <span className="text-white text-xs font-bold">None</span>
                  </div>
                  <div className="flex justify-between items-center py-1">
                    <span className="text-text-secondary text-xs">Initiator Group</span>
                    {initiatorGroups.length > 0 ? (
                      <div className="flex flex-col items-end gap-1">
                        {initiatorGroups.map((group) => (
                          <div key={group.id} className="flex items-center gap-2">
                            <span className="text-primary text-xs font-bold">{group.group_name}</span>
                            <span className="text-text-secondary text-xs">
                              ({group.initiators?.length || 0} initiators)
                            </span>
                          </div>
                        ))}
                      </div>
                    ) : (
                      <span className="text-text-secondary text-xs">None</span>
                    )}
                  </div>
                  {initiatorGroups.length > 0 && (
                    <div className="pt-2 border-t border-border-dark/50">
                      <div className="flex flex-col gap-1">
                        {initiatorGroups.flatMap(group => 
                          (group.initiators || []).map(initiator => (
                            <div key={initiator.id} className="text-text-secondary text-xs font-mono">
                              {initiator.iqn}
                            </div>
                          ))
                        )}
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>

            {/* Action Footer */}
            <div className="col-span-1 lg:col-span-2 flex justify-end gap-2 mt-2 pt-3 border-t border-border-dark/50">
              <Link
                to={`/iscsi/${target.id}`}
                className="px-3 py-1.5 rounded text-xs font-bold bg-primary text-white hover:bg-blue-600 transition-colors"
              >
                View Details
              </Link>
            </div>
          </div>
        </div>
      )}

      {/* Edit Policy Modal */}
      {showEditPolicy && (
        <EditPolicyModal
          target={target}
          initiatorGroups={initiatorGroups}
          onClose={() => setShowEditPolicy(false)}
          onSuccess={() => {
            queryClient.invalidateQueries({ queryKey: ['scst-target', target.id] })
            setShowEditPolicy(false)
          }}
        />
      )}
    </div>
  )
}

interface EditPolicyModalProps {
  target: SCSTTarget
  initiatorGroups: SCSTInitiatorGroup[]
  onClose: () => void
  onSuccess: () => void
}

function EditPolicyModal({ target, initiatorGroups, onClose, onSuccess }: EditPolicyModalProps) {
  const [initiatorIQN, setInitiatorIQN] = useState('')
  const queryClient = useQueryClient()

  const addInitiatorMutation = useMutation({
    mutationFn: (iqn: string) => scstAPI.addInitiator(target.id, { initiator_iqn: iqn }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scst-target', target.id] })
      setInitiatorIQN('')
      onSuccess()
    },
    onError: (error: any) => {
      alert(`Failed to add initiator: ${error.response?.data?.error || error.message}`)
    },
  })

  const removeInitiatorMutation = useMutation({
    mutationFn: (initiatorId: string) => scstAPI.removeInitiator(initiatorId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scst-target', target.id] })
      queryClient.invalidateQueries({ queryKey: ['scst-initiators'] })
      onSuccess()
    },
    onError: (error: any) => {
      alert(`Failed to remove initiator: ${error.response?.data?.error || error.message}`)
    },
  })

  const handleAddInitiator = (e: React.FormEvent) => {
    e.preventDefault()
    if (!initiatorIQN.trim()) {
      alert('Please enter an initiator IQN')
      return
    }
    addInitiatorMutation.mutate(initiatorIQN.trim())
  }

  // Flatten all initiators from all groups
  const allInitiators = initiatorGroups.flatMap(group => group.initiators || [])

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4" onClick={onClose}>
      <div 
        className="bg-card-dark border border-border-dark rounded-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="p-6 border-b border-border-dark flex items-center justify-between">
          <div>
            <h2 className="text-xl font-bold text-white">Edit Access Policy</h2>
            <p className="text-sm text-text-secondary mt-1">Manage initiators for {target.iqn}</p>
          </div>
          <button
            onClick={onClose}
            className="p-2 hover:bg-white/10 rounded-lg text-text-secondary hover:text-white transition-colors"
          >
            <X size={20} />
          </button>
        </div>

        <div className="p-6 space-y-6">
          {/* Add Initiator Form */}
          <div>
            <h3 className="text-sm font-bold text-white mb-3">Add Initiator</h3>
            <form onSubmit={handleAddInitiator} className="flex gap-2">
              <input
                type="text"
                value={initiatorIQN}
                onChange={(e) => setInitiatorIQN(e.target.value)}
                placeholder="iqn.2025-12.example:initiator"
                className="flex-1 px-3 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                required
              />
              <Button
                type="submit"
                disabled={addInitiatorMutation.isPending}
                className="px-4 bg-primary hover:bg-blue-600"
              >
                {addInitiatorMutation.isPending ? 'Adding...' : 'Add'}
              </Button>
            </form>
          </div>

          {/* Current Initiators */}
          <div>
            <h3 className="text-sm font-bold text-white mb-3">
              Current Initiators ({allInitiators.length})
            </h3>
            {allInitiators.length > 0 ? (
              <div className="space-y-2">
                {allInitiators.map((initiator) => (
                  <div
                    key={initiator.id}
                    className="p-3 rounded bg-[#0f161d] border border-border-dark flex items-center justify-between"
                  >
                    <div className="flex items-center gap-3">
                      <div className="p-2 rounded bg-primary/10 text-primary">
                        <Network size={16} />
                      </div>
                      <div>
                        <div className="text-white text-sm font-mono">{initiator.iqn}</div>
                        <div className="text-text-secondary text-xs">
                          {initiator.is_active ? 'Active' : 'Inactive'}
                        </div>
                      </div>
                    </div>
                    <button
                      onClick={() => {
                        if (confirm(`Remove initiator ${initiator.iqn}?`)) {
                          removeInitiatorMutation.mutate(initiator.id)
                        }
                      }}
                      disabled={removeInitiatorMutation.isPending}
                      className="p-2 hover:bg-red-500/10 rounded-lg text-text-secondary hover:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                      title="Remove initiator"
                    >
                      <Trash2 size={16} />
                    </button>
                  </div>
                ))}
              </div>
            ) : (
              <div className="p-4 rounded bg-[#0f161d] border border-border-dark text-center text-text-secondary text-sm">
                No initiators configured
              </div>
            )}
          </div>

          {/* Auth Method (Placeholder) */}
          <div>
            <h3 className="text-sm font-bold text-white mb-3">Authentication Method</h3>
            <div className="p-3 rounded bg-[#0f161d] border border-border-dark">
              <div className="flex items-center justify-between">
                <span className="text-text-secondary text-sm">Current Method</span>
                <span className="text-white text-sm font-bold">None</span>
              </div>
              <p className="text-text-secondary text-xs mt-2">
                Authentication configuration coming soon
              </p>
            </div>
          </div>
        </div>

        <div className="p-6 border-t border-border-dark flex justify-end gap-2">
          <Button
            variant="outline"
            onClick={onClose}
            className="px-4"
          >
            Close
          </Button>
        </div>
      </div>
    </div>
  )
}

interface CreateTargetFormProps {
  onClose: () => void
  onSuccess: () => void
}

function CreateTargetForm({ onClose, onSuccess }: CreateTargetFormProps) {
  const [iqn, setIqn] = useState('')
  const [name, setName] = useState('')
  const [targetType, setTargetType] = useState('disk')
  const [description, setDescription] = useState('')

  const queryClient = useQueryClient()
  
  const createMutation = useMutation({
    mutationFn: scstAPI.createTarget,
    onSuccess: async (newTarget) => {
      // Invalidate and refetch targets list to ensure we get the latest data
      await queryClient.invalidateQueries({ queryKey: ['scst-targets'] })
      await queryClient.refetchQueries({ queryKey: ['scst-targets'] })
      // Also invalidate the specific target query if it exists
      if (newTarget?.id) {
        await queryClient.invalidateQueries({ queryKey: ['scst-target', newTarget.id] })
      }
      onSuccess()
    },
    onError: (error: any) => {
      console.error('Failed to create target:', error)
      const errorMessage = error.response?.data?.error || error.message || 'Failed to create target'
      alert(errorMessage)
    },
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!iqn.trim() || !name.trim()) {
      alert('IQN and Name are required')
      return
    }

    const targetData = {
      iqn: iqn.trim(),
      target_type: targetType,
      name: name.trim(),
      description: description.trim() || undefined,
    }

    console.log('Creating target:', targetData)
    createMutation.mutate(targetData)
  }

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
      <div className="bg-card-dark border border-border-dark rounded-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto">
        <div className="p-6 border-b border-border-dark">
          <h2 className="text-xl font-bold text-white">Create iSCSI Target</h2>
          <p className="text-sm text-text-secondary mt-1">Create a new SCST iSCSI target</p>
        </div>
        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          <div>
            <label htmlFor="iqn" className="block text-sm font-medium text-white mb-1">
              IQN (iSCSI Qualified Name) *
            </label>
            <input
              id="iqn"
              type="text"
              value={iqn}
              onChange={(e) => setIqn(e.target.value)}
              placeholder="iqn.2024-01.com.example:target1"
              className="w-full px-3 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
              required
            />
            <p className="mt-1 text-xs text-text-secondary">
              Format: iqn.YYYY-MM.reverse.domain:identifier
            </p>
          </div>

          <div>
            <label htmlFor="name" className="block text-sm font-medium text-white mb-1">
              Name *
            </label>
            <input
              id="name"
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="My Target"
              className="w-full px-3 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
              required
            />
          </div>

          <div>
            <label htmlFor="targetType" className="block text-sm font-medium text-white mb-1">
              Target Type *
            </label>
            <select
              id="targetType"
              value={targetType}
              onChange={(e) => setTargetType(e.target.value)}
              className="w-full px-3 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
              required
            >
              <option value="disk">Disk</option>
              <option value="vtl">Virtual Tape Library</option>
              <option value="physical_tape">Physical Tape</option>
            </select>
          </div>

          <div>
            <label htmlFor="description" className="block text-sm font-medium text-white mb-1">
              Description (Optional)
            </label>
            <textarea
              id="description"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Target description"
              className="w-full px-3 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
              rows={3}
            />
          </div>

          <div className="flex justify-end gap-2 pt-4 border-t border-border-dark">
            <Button type="button" variant="outline" onClick={onClose}>
              Cancel
            </Button>
            <Button type="submit" disabled={createMutation.isPending}>
              {createMutation.isPending ? 'Creating...' : 'Create Target'}
            </Button>
          </div>
        </form>
      </div>
    </div>
  )
}

function PortalsTab() {
  const queryClient = useQueryClient()
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [editingPortal, setEditingPortal] = useState<SCSTPortal | null>(null)

  const { data: portals = [], isLoading } = useQuery<SCSTPortal[]>({
    queryKey: ['scst-portals'],
    queryFn: scstAPI.listPortals,
  })

  const deleteMutation = useMutation({
    mutationFn: scstAPI.deletePortal,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scst-portals'] })
    },
    onError: (error: any) => {
      alert(`Failed to delete portal: ${error.response?.data?.error || error.message}`)
    },
  })

  const handleDelete = (portal: SCSTPortal) => {
    if (confirm(`Delete portal ${portal.ip_address}:${portal.port}?`)) {
      deleteMutation.mutate(portal.id)
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-white text-2xl font-bold">iSCSI Portals</h2>
          <p className="text-text-secondary text-sm mt-1">Manage network portals for iSCSI connections</p>
        </div>
        <Button
          onClick={() => setShowCreateModal(true)}
          className="flex items-center gap-2 px-4 h-10 rounded-lg bg-primary hover:bg-blue-600 text-white text-sm font-bold"
        >
          <Plus size={20} />
          <span>Create Portal</span>
        </Button>
      </div>

      {/* Portals List */}
      {isLoading ? (
        <div className="p-8 text-center text-text-secondary">Loading portals...</div>
      ) : portals.length > 0 ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {portals.map((portal) => (
            <div
              key={portal.id}
              className="p-4 rounded-lg bg-card-dark border border-border-dark hover:border-primary/50 transition-colors"
            >
              <div className="flex items-start justify-between mb-3">
                <div className="flex items-center gap-2">
                  <Network size={20} className="text-primary" />
                  <div>
                    <div className="text-white font-bold text-sm">{portal.ip_address}</div>
                    <div className="text-text-secondary text-xs">Port: {portal.port}</div>
                  </div>
                </div>
                <span
                  className={`px-2 py-1 rounded text-xs font-bold ${
                    portal.is_active
                      ? 'bg-green-500/20 text-green-400 border border-green-500/20'
                      : 'bg-gray-500/20 text-gray-400 border border-gray-500/20'
                  }`}
                >
                  {portal.is_active ? 'Active' : 'Inactive'}
                </span>
              </div>
              <div className="flex gap-2 mt-4">
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setEditingPortal(portal)}
                  className="flex-1 text-xs"
                >
                  Edit
                </Button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => handleDelete(portal)}
                  disabled={deleteMutation.isPending}
                  className="flex-1 text-xs text-red-400 hover:text-red-300 hover:bg-red-500/10"
                >
                  Delete
                </Button>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <div className="p-12 text-center rounded-lg bg-card-dark border border-border-dark">
          <Network size={48} className="mx-auto text-text-secondary mb-4" />
          <p className="text-text-secondary">No portals configured</p>
          <p className="text-text-secondary text-sm mt-1">Create a portal to start accepting iSCSI connections</p>
        </div>
      )}

      {/* Create/Edit Modal */}
      {(showCreateModal || editingPortal) && (
        <PortalFormModal
          portal={editingPortal}
          onClose={() => {
            setShowCreateModal(false)
            setEditingPortal(null)
          }}
          onSuccess={() => {
            queryClient.invalidateQueries({ queryKey: ['scst-portals'] })
            setShowCreateModal(false)
            setEditingPortal(null)
          }}
        />
      )}
    </div>
  )
}

interface PortalFormModalProps {
  portal?: SCSTPortal | null
  onClose: () => void
  onSuccess: () => void
}

function PortalFormModal({ portal, onClose, onSuccess }: PortalFormModalProps) {
  const [ipAddress, setIpAddress] = useState(portal?.ip_address || '0.0.0.0')
  const [port, setPort] = useState(portal?.port || 3260)
  const [isActive, setIsActive] = useState(portal?.is_active ?? true)
  const queryClient = useQueryClient()

  const createMutation = useMutation({
    mutationFn: (data: { ip_address: string; port: number; is_active: boolean }) =>
      scstAPI.createPortal(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scst-portals'] })
      onSuccess()
    },
    onError: (error: any) => {
      alert(`Failed to create portal: ${error.response?.data?.error || error.message}`)
    },
  })

  const updateMutation = useMutation({
    mutationFn: (data: { ip_address: string; port: number; is_active: boolean }) =>
      scstAPI.updatePortal(portal!.id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scst-portals'] })
      onSuccess()
    },
    onError: (error: any) => {
      alert(`Failed to update portal: ${error.response?.data?.error || error.message}`)
    },
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    const data = {
      ip_address: ipAddress.trim(),
      port: parseInt(port.toString()),
      is_active: isActive,
    }

    if (portal) {
      updateMutation.mutate(data)
    } else {
      createMutation.mutate(data)
    }
  }

  const isLoading = createMutation.isPending || updateMutation.isPending

  return (
    <div className="fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4" onClick={onClose}>
      <div
        className="bg-card-dark border border-border-dark rounded-xl max-w-md w-full"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="p-6 border-b border-border-dark flex items-center justify-between">
          <h2 className="text-xl font-bold text-white">
            {portal ? 'Edit Portal' : 'Create Portal'}
          </h2>
          <button
            onClick={onClose}
            className="p-2 hover:bg-white/10 rounded-lg text-text-secondary hover:text-white transition-colors"
          >
            <X size={20} />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-4">
          <div>
            <label htmlFor="ipAddress" className="block text-sm font-medium text-white mb-1">
              IP Address *
            </label>
            <input
              id="ipAddress"
              type="text"
              value={ipAddress}
              onChange={(e) => setIpAddress(e.target.value)}
              placeholder="0.0.0.0 (all interfaces) or specific IP"
              className="w-full px-3 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
              required
            />
            <p className="mt-1 text-xs text-text-secondary">
              Use 0.0.0.0 to listen on all interfaces, or specify an IP address
            </p>
          </div>

          <div>
            <label htmlFor="port" className="block text-sm font-medium text-white mb-1">
              Port *
            </label>
            <input
              id="port"
              type="number"
              value={port}
              onChange={(e) => setPort(parseInt(e.target.value) || 3260)}
              min="1"
              max="65535"
              className="w-full px-3 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
              required
            />
            <p className="mt-1 text-xs text-text-secondary">Default iSCSI port is 3260</p>
          </div>

          <div className="flex items-center gap-2">
            <input
              id="isActive"
              type="checkbox"
              checked={isActive}
              onChange={(e) => setIsActive(e.target.checked)}
              className="w-4 h-4 rounded bg-[#0f161d] border-border-dark text-primary focus:ring-primary"
            />
            <label htmlFor="isActive" className="text-sm text-white">
              Active
            </label>
          </div>

          <div className="flex justify-end gap-2 pt-4 border-t border-border-dark">
            <Button type="button" variant="outline" onClick={onClose} disabled={isLoading}>
              Cancel
            </Button>
            <Button type="submit" disabled={isLoading}>
              {isLoading ? (portal ? 'Updating...' : 'Creating...') : portal ? 'Update' : 'Create'}
            </Button>
          </div>
        </form>
      </div>
    </div>
  )
}

function InitiatorsTab() {
  const queryClient = useQueryClient()
  const [searchQuery, setSearchQuery] = useState('')
  const [statusFilter, setStatusFilter] = useState<string>('all')

  const { data: initiators = [], isLoading } = useQuery<SCSTInitiator[]>({
    queryKey: ['scst-initiators'],
    queryFn: scstAPI.listInitiators,
  })

  const deleteMutation = useMutation({
    mutationFn: scstAPI.removeInitiator,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scst-initiators'] })
      queryClient.invalidateQueries({ queryKey: ['scst-targets'] })
    },
    onError: (error: any) => {
      alert(`Failed to remove initiator: ${error.response?.data?.error || error.message}`)
    },
  })

  const filteredInitiators = initiators.filter(initiator => {
    const matchesSearch = initiator.iqn.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (initiator.target_iqn && initiator.target_iqn.toLowerCase().includes(searchQuery.toLowerCase())) ||
      (initiator.target_name && initiator.target_name.toLowerCase().includes(searchQuery.toLowerCase()))
    
    const matchesStatus = statusFilter === 'all' ||
      (statusFilter === 'active' && initiator.is_active) ||
      (statusFilter === 'inactive' && !initiator.is_active)

    return matchesSearch && matchesStatus
  })

  const handleDelete = (initiator: SCSTInitiator) => {
    if (confirm(`Remove initiator ${initiator.iqn}?`)) {
      deleteMutation.mutate(initiator.id)
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-white text-2xl font-bold">iSCSI Initiators</h2>
          <p className="text-text-secondary text-sm mt-1">Manage initiator access control lists</p>
        </div>
      </div>

      {/* Toolbar */}
      <div className="p-4 flex items-center justify-between gap-4 border-b border-border-dark/50 bg-[#141d26]">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-text-secondary" size={20} />
          <input
            type="text"
            placeholder="Search initiators by IQN or target..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full bg-[#0f161d] border border-border-dark rounded-lg pl-10 pr-4 py-2 text-sm text-white focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all placeholder-text-secondary/50"
          />
        </div>
        <div className="flex items-center gap-3">
          <div className="flex items-center gap-2 px-3 py-1.5 rounded-md bg-[#0f161d] border border-border-dark">
            <span className="text-xs text-text-secondary font-medium">Filter:</span>
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="bg-[#0f161d] text-xs text-white font-medium focus:outline-none cursor-pointer border-none appearance-none pr-6"
              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='%23999' d='M6 9L1 4h10z'/%3E%3C/svg%3E")`,
                backgroundRepeat: 'no-repeat',
                backgroundPosition: 'right 0 center',
                paddingRight: '24px'
              }}
            >
              <option value="all" className="bg-[#0f161d] text-white">All Status</option>
              <option value="active" className="bg-[#0f161d] text-white">Active</option>
              <option value="inactive" className="bg-[#0f161d] text-white">Inactive</option>
            </select>
          </div>
        </div>
      </div>

      {/* Initiators List */}
      {isLoading ? (
        <div className="p-8 text-center text-text-secondary">Loading initiators...</div>
      ) : filteredInitiators.length > 0 ? (
        <div className="bg-[#141d26] border border-border-dark rounded-lg overflow-hidden">
          <div className="divide-y divide-border-dark">
            {filteredInitiators.map((initiator) => (
              <div
                key={initiator.id}
                className="p-4 hover:bg-white/5 transition-colors flex items-center justify-between gap-4"
              >
                <div className="flex-1 min-w-0 flex items-center gap-4">
                  <div className="p-2 rounded-md bg-primary/10 text-primary">
                    <Network size={20} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-3 mb-1">
                      <span className="text-white font-mono text-sm font-medium truncate">
                        {initiator.iqn}
                      </span>
                      <span className={`px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wide border ${
                        initiator.is_active
                          ? 'bg-green-500/20 text-green-400 border-green-500/20'
                          : 'bg-red-500/20 text-red-400 border-red-500/20'
                      }`}>
                        {initiator.is_active ? 'Active' : 'Inactive'}
                      </span>
                    </div>
                    <div className="flex items-center gap-4 text-xs text-text-secondary flex-wrap mt-1">
                      {initiator.target_iqn && (
                        <div className="flex items-center gap-1.5">
                          <span className="font-semibold text-text-secondary/80">Target:</span>
                          <span className="font-mono text-white/90 truncate max-w-[300px]" title={initiator.target_iqn}>
                            {initiator.target_name || initiator.target_iqn.split(':').pop()}
                          </span>
                        </div>
                      )}
                      {initiator.group_name && (
                        <div className="flex items-center gap-1.5">
                          <span className="font-semibold text-text-secondary/80">Group:</span>
                          <span className="font-mono text-white/90 truncate max-w-[300px]" title={initiator.group_name}>
                            {initiator.group_name}
                          </span>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => {
                      navigator.clipboard.writeText(initiator.iqn)
                    }}
                    className="p-2 hover:bg-white/10 rounded-lg text-text-secondary hover:text-white transition-colors"
                    title="Copy IQN"
                  >
                    <Copy size={16} />
                  </button>
                  <button
                    onClick={() => handleDelete(initiator)}
                    disabled={deleteMutation.isPending}
                    className="p-2 hover:bg-red-500/10 rounded-lg text-text-secondary hover:text-red-400 transition-colors"
                    title="Remove initiator"
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div className="p-12 text-center">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-border-dark/50 mb-4">
            <Network className="text-text-secondary" size={32} />
          </div>
          <p className="text-white font-medium mb-1">No initiators found</p>
          <p className="text-text-secondary text-sm">
            {searchQuery || statusFilter !== 'all'
              ? 'Try adjusting your search or filter criteria'
              : 'Initiators will appear here once they are added to targets'}
          </p>
        </div>
      )}
    </div>
  )
}

function ExtentsTab() {
  const queryClient = useQueryClient()
  const [searchQuery, setSearchQuery] = useState('')
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [handlers, setHandlers] = useState<Array<{ name: string; label: string; description?: string }>>([])

  const { data: extents = [], isLoading } = useQuery<SCSTExtent[]>({
    queryKey: ['scst-extents'],
    queryFn: () => scstAPI.listExtents(), // Wrap in arrow function to ensure fresh call
    refetchInterval: 3000, // Auto-refresh every 3 seconds
    refetchIntervalInBackground: true, // Continue refetching even when tab is in background
    refetchOnWindowFocus: true, // Refetch when window regains focus
    refetchOnMount: true, // Always refetch on mount
    refetchOnReconnect: true, // Refetch when network reconnects
    staleTime: 0, // Consider data stale immediately to ensure fresh data
    gcTime: 0, // Don't cache data (formerly cacheTime)
    structuralSharing: false, // Disable structural sharing to ensure updates are detected
  })

  const { data: handlersData } = useQuery({
    queryKey: ['scst-handlers'],
    queryFn: scstAPI.listHandlers,
  })

  // Update handlers when data changes
  useEffect(() => {
    if (handlersData) {
      setHandlers(handlersData.map(h => ({ name: h.name, label: h.label, description: h.description })))
    }
  }, [handlersData])

  const deleteMutation = useMutation({
    mutationFn: scstAPI.deleteExtent,
    onMutate: async (deviceName: string) => {
      // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
      await queryClient.cancelQueries({ queryKey: ['scst-extents'] })
      await queryClient.cancelQueries({ queryKey: ['scst-targets'] })

      // Snapshot the previous value
      const previousExtents = queryClient.getQueryData<SCSTExtent[]>(['scst-extents'])

      // Optimistically update to remove the extent
      queryClient.setQueryData<SCSTExtent[]>(['scst-extents'], (old) =>
        old ? old.filter((e) => e.device_name !== deviceName) : []
      )

      return { previousExtents }
    },
    onSuccess: async () => {
      // Remove all queries from cache (including inactive ones)
      queryClient.removeQueries({ queryKey: ['scst-extents'] })
      queryClient.removeQueries({ queryKey: ['scst-targets'] })
      
      // Invalidate all related queries
      await queryClient.invalidateQueries({ queryKey: ['scst-extents'] })
      await queryClient.invalidateQueries({ queryKey: ['scst-targets'] })
      
      // Force refetch with no cache
      await queryClient.refetchQueries({ 
        queryKey: ['scst-extents'],
        type: 'all' // Refetch all queries, not just active
      })
      
      // Also refetch targets to update LUN count if needed
      await queryClient.refetchQueries({ 
        queryKey: ['scst-targets'],
        type: 'all'
      })
    },
    onError: (error: any, _deviceName: string, context) => {
      // Rollback optimistic update
      if (context?.previousExtents) {
        queryClient.setQueryData<SCSTExtent[]>(['scst-extents'], context.previousExtents)
      }
      
      // Refetch to restore correct state
      queryClient.refetchQueries({ queryKey: ['scst-extents'] })
      alert(`Failed to delete extent: ${error.response?.data?.error || error.message}`)
    },
  })

  const filteredExtents = extents.filter(extent => {
    return extent.device_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      extent.device_path.toLowerCase().includes(searchQuery.toLowerCase()) ||
      extent.handler_type.toLowerCase().includes(searchQuery.toLowerCase())
  })

  const handleDelete = (extent: SCSTExtent) => {
    if (extent.is_in_use) {
      alert(`Cannot delete extent ${extent.device_name}: it is in use by ${extent.lun_count} LUN(s)`)
      return
    }
    if (confirm(`Delete extent ${extent.device_name}?`)) {
      deleteMutation.mutate(extent.device_name)
    }
  }

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-white text-2xl font-bold">iSCSI Extents</h2>
          <p className="text-text-secondary text-sm mt-1">Manage device extents (opened devices) for iSCSI LUNs</p>
        </div>
        <Button
          onClick={() => setShowCreateModal(true)}
          className="flex items-center gap-2 px-4 h-10 rounded-lg bg-primary hover:bg-blue-600 text-white text-sm font-bold"
        >
          <Plus size={20} />
          <span>Create Extent</span>
        </Button>
      </div>

      <div className="p-4 flex items-center justify-between gap-4 border-b border-border-dark/50 bg-[#141d26]">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-text-secondary" size={20} />
          <input
            type="text"
            placeholder="Search extents by device name, path, or handler..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full bg-[#0f161d] border border-border-dark rounded-lg pl-10 pr-4 py-2 text-sm text-white focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all placeholder-text-secondary/50"
          />
        </div>
      </div>

      {isLoading ? (
        <div className="p-8 text-center text-text-secondary">Loading extents...</div>
      ) : filteredExtents.length > 0 ? (
        <div className="bg-[#141d26] border border-border-dark rounded-lg overflow-hidden">
          <div className="divide-y divide-border-dark">
            {filteredExtents.map((extent, idx) => (
              <div
                key={`${extent.handler_type}-${extent.device_name}-${idx}`}
                className="p-4 hover:bg-white/5 transition-colors flex items-center justify-between gap-4"
              >
                <div className="flex-1 min-w-0 flex items-center gap-4">
                  <div className={`p-2 rounded-md ${extent.is_in_use ? 'bg-yellow-500/10 text-yellow-400' : 'bg-primary/10 text-primary'}`}>
                    <HardDrive size={20} />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-3 mb-1">
                      <span className="text-white font-mono text-sm font-medium">
                        {extent.device_name}
                      </span>
                      {extent.is_in_use && (
                        <span className="px-2 py-0.5 rounded-full text-[10px] font-bold uppercase tracking-wide border bg-yellow-500/20 text-yellow-400 border-yellow-500/20">
                          In Use ({extent.lun_count} LUN{extent.lun_count !== 1 ? 's' : ''})
                        </span>
                      )}
                    </div>
                    <div className="flex items-center gap-4 text-xs text-text-secondary">
                      <div className="flex items-center gap-1">
                        <span className="font-medium">Handler:</span>
                        <span className="truncate">{extent.handler_type}</span>
                      </div>
                      {extent.device_path && (
                        <div className="flex items-center gap-1">
                          <span className="font-medium">Path:</span>
                          <span className="font-mono truncate max-w-[400px]">{extent.device_path}</span>
                        </div>
                      )}
                    </div>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <button
                    onClick={() => {
                      if (extent.device_path) {
                        navigator.clipboard.writeText(extent.device_path)
                      }
                    }}
                    className="p-2 hover:bg-white/10 rounded-lg text-text-secondary hover:text-white transition-colors"
                    title="Copy device path"
                  >
                    <Copy size={16} />
                  </button>
                  <button
                    onClick={() => handleDelete(extent)}
                    disabled={deleteMutation.isPending || extent.is_in_use}
                    className="p-2 hover:bg-red-500/10 rounded-lg text-text-secondary hover:text-red-400 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                    title={extent.is_in_use ? "Cannot delete: extent is in use" : "Delete extent"}
                  >
                    <Trash2 size={16} />
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div className="p-12 text-center">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-border-dark/50 mb-4">
            <HardDrive className="text-text-secondary" size={32} />
          </div>
          <p className="text-white font-medium mb-1">No extents found</p>
          <p className="text-text-secondary text-sm">
            {searchQuery
              ? 'Try adjusting your search criteria'
              : 'Create an extent to make a device available for iSCSI LUNs'}
          </p>
        </div>
      )}

      {showCreateModal && (
        <CreateExtentModal
          handlers={handlers}
          onClose={() => setShowCreateModal(false)}
          onSuccess={async () => {
            setShowCreateModal(false)
            // Remove queries from cache
            queryClient.removeQueries({ queryKey: ['scst-extents'] })
            // Force refetch to ensure fresh data
            await queryClient.invalidateQueries({ queryKey: ['scst-extents'] })
            await queryClient.refetchQueries({ 
              queryKey: ['scst-extents'],
              type: 'active'
            })
          }}
        />
      )}
    </div>
  )
}

function CreateExtentModal({ handlers, onClose, onSuccess }: { handlers: Array<{ name: string; label: string; description?: string }>, onClose: () => void, onSuccess: () => Promise<void> }) {
  const [deviceName, setDeviceName] = useState('')
  const [devicePath, setDevicePath] = useState('')
  const [handlerType, setHandlerType] = useState('')

  const createMutation = useMutation({
    mutationFn: (data: CreateExtentRequest) => scstAPI.createExtent(data),
    onSuccess: async () => {
      // Call onSuccess callback which will handle refresh
      await onSuccess()
      alert('Extent created successfully!')
    },
    onError: (error: any) => {
      alert(`Failed to create extent: ${error.response?.data?.error || error.message}`)
    },
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!deviceName || !devicePath || !handlerType) {
      alert('Please fill in all required fields')
      return
    }
    createMutation.mutate({
      device_name: deviceName,
      device_path: devicePath,
      handler_type: handlerType,
    })
  }

  const handlePathChange = (path: string) => {
    setDevicePath(path)
    if (!deviceName && path) {
      const parts = path.split('/')
      const name = parts[parts.length - 1]
      if (name) {
        setDeviceName(name)
      }
    }
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-[#141d26] border border-border-dark rounded-lg p-6 w-full max-w-md">
        <div className="flex items-center justify-between mb-4">
          <h3 className="text-white text-lg font-bold">Create Extent</h3>
          <button
            onClick={onClose}
            className="text-text-secondary hover:text-white transition-colors"
          >
            <X size={20} />
          </button>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label htmlFor="handlerType" className="block text-sm font-medium text-white mb-1">
              Handler Type *
            </label>
            <select
              id="handlerType"
              value={handlerType}
              onChange={(e) => setHandlerType(e.target.value)}
              className="w-full px-3 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
              required
            >
              <option value="">Select handler...</option>
              {handlers.map((h) => (
                <option key={h.name} value={h.name} className="bg-[#0f161d] text-white">
                  {h.label || h.name} - {h.description}
                </option>
              ))}
            </select>
          </div>

          <div>
            <label htmlFor="devicePath" className="block text-sm font-medium text-white mb-1">
              Device Path *
            </label>
            <input
              id="devicePath"
              type="text"
              value={devicePath}
              onChange={(e) => handlePathChange(e.target.value)}
              placeholder="/dev/zvol/pool/volume or /path/to/file"
              className="w-full px-3 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
              required
            />
            <p className="mt-1 text-xs text-text-secondary">Full path to the device or file</p>
          </div>

          <div>
            <label htmlFor="deviceName" className="block text-sm font-medium text-white mb-1">
              Device Name *
            </label>
            <input
              id="deviceName"
              type="text"
              value={deviceName}
              onChange={(e) => setDeviceName(e.target.value)}
              placeholder="LUN01"
              className="w-full px-3 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
              required
            />
            <p className="mt-1 text-xs text-text-secondary">Unique name for this device in SCST</p>
          </div>

          <div className="flex justify-end gap-2 pt-4 border-t border-border-dark">
            <Button type="button" variant="outline" onClick={onClose} disabled={createMutation.isPending}>
              Cancel
            </Button>
            <Button type="submit" disabled={createMutation.isPending}>
              {createMutation.isPending ? 'Creating...' : 'Create Extent'}
            </Button>
          </div>
        </form>
      </div>
    </div>
  )
}

function InitiatorGroupsTab() {
  const queryClient = useQueryClient()
  const [searchQuery, setSearchQuery] = useState('')
  const [showCreateModal, setShowCreateModal] = useState(false)
  const [editingGroup, setEditingGroup] = useState<SCSTInitiatorGroup | null>(null)
  const [expandedGroup, setExpandedGroup] = useState<string | null>(null)
  const [showAddInitiatorModal, setShowAddInitiatorModal] = useState<string | null>(null)

  const { data: groups = [], isLoading } = useQuery<SCSTInitiatorGroup[]>({
    queryKey: ['scst-initiator-groups'],
    queryFn: scstAPI.listInitiatorGroups,
    refetchInterval: 3000, // Auto-refresh every 3 seconds
    refetchIntervalInBackground: true, // Continue refetching even when tab is in background
    refetchOnWindowFocus: true, // Refetch when window regains focus
    refetchOnMount: true, // Always refetch on mount
    refetchOnReconnect: true, // Refetch when network reconnects
    staleTime: 0, // Consider data stale immediately to ensure fresh data
    gcTime: 0, // Don't cache data (formerly cacheTime)
    structuralSharing: false, // Disable structural sharing to ensure updates are detected
  })

  const { data: targets = [] } = useQuery<SCSTTarget[]>({
    queryKey: ['scst-targets'],
    queryFn: scstAPI.listTargets,
  })

  const createMutation = useMutation({
    mutationFn: (data: { target_id: string; group_name: string }) => scstAPI.createInitiatorGroup(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scst-initiator-groups'] })
      queryClient.invalidateQueries({ queryKey: ['scst-targets'] })
      setShowCreateModal(false)
    },
    onError: (error: any) => {
      alert(`Failed to create group: ${error.response?.data?.error || error.message}`)
    },
  })

  const updateMutation = useMutation({
    mutationFn: ({ id, data }: { id: string; data: { group_name: string } }) => scstAPI.updateInitiatorGroup(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scst-initiator-groups'] })
      queryClient.invalidateQueries({ queryKey: ['scst-targets'] })
      setEditingGroup(null)
    },
    onError: (error: any) => {
      alert(`Failed to update group: ${error.response?.data?.error || error.message}`)
    },
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => scstAPI.deleteInitiatorGroup(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scst-initiator-groups'] })
      queryClient.invalidateQueries({ queryKey: ['scst-targets'] })
    },
    onError: (error: any) => {
      alert(`Failed to delete group: ${error.response?.data?.error || error.message}`)
    },
  })

  const addInitiatorMutation = useMutation({
    mutationFn: ({ groupId, initiatorIQN }: { groupId: string; initiatorIQN: string }) => 
      scstAPI.addInitiatorToGroup(groupId, initiatorIQN),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scst-initiator-groups'] })
      queryClient.invalidateQueries({ queryKey: ['scst-targets'] })
      queryClient.invalidateQueries({ queryKey: ['scst-initiators'] })
      setShowAddInitiatorModal(null)
    },
    onError: (error: any) => {
      alert(`Failed to add initiator: ${error.response?.data?.error || error.message}`)
    },
  })

  const removeInitiatorMutation = useMutation({
    mutationFn: (initiatorId: string) => scstAPI.removeInitiator(initiatorId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['scst-initiator-groups'] })
      queryClient.invalidateQueries({ queryKey: ['scst-targets'] })
      queryClient.invalidateQueries({ queryKey: ['scst-initiators'] })
    },
    onError: (error: any) => {
      alert(`Failed to remove initiator: ${error.response?.data?.error || error.message}`)
    },
  })

  const filteredGroups = groups.filter(group => {
    const target = targets.find(t => t.id === group.target_id)
    const matchesSearch = 
      group.group_name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (target && ((target.alias || target.iqn).toLowerCase().includes(searchQuery.toLowerCase()) || target.iqn.toLowerCase().includes(searchQuery.toLowerCase())))
    return matchesSearch
  })

  const handleDelete = (group: SCSTInitiatorGroup) => {
    if (group.initiators && group.initiators.length > 0) {
      alert(`Cannot delete group: Group contains ${group.initiators.length} initiator(s). Please remove all initiators first.`)
      return
    }
    if (confirm(`Delete initiator group "${group.group_name}"?`)) {
      deleteMutation.mutate(group.id)
    }
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h2 className="text-white text-2xl font-bold">iSCSI Initiator Groups</h2>
          <p className="text-text-secondary text-sm mt-1">Manage initiator access control groups</p>
        </div>
        <Button onClick={() => setShowCreateModal(true)}>
          <Plus size={16} className="mr-2" />
          Create Group
        </Button>
      </div>

      {/* Toolbar */}
      <div className="p-4 flex items-center justify-between gap-4 border-b border-border-dark/50 bg-[#141d26]">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 text-text-secondary" size={20} />
          <input
            type="text"
            placeholder="Search groups by name or target..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="w-full bg-[#0f161d] border border-border-dark rounded-lg pl-10 pr-4 py-2 text-sm text-white focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary transition-all placeholder-text-secondary/50"
          />
        </div>
      </div>

      {/* Groups List */}
      {isLoading ? (
        <div className="p-8 text-center text-text-secondary">Loading groups...</div>
      ) : filteredGroups.length > 0 ? (
        <div className="bg-[#141d26] border border-border-dark rounded-lg overflow-hidden">
          <div className="divide-y divide-border-dark">
            {filteredGroups.map((group) => {
              const target = targets.find(t => t.id === group.target_id)
              const isExpanded = expandedGroup === group.id
              return (
                <div
                  key={group.id}
                  className="border-b border-border-dark last:border-b-0"
                >
                  <div className="p-4 hover:bg-white/5 transition-colors">
                    <div className="flex items-start justify-between gap-4">
                      <div className="flex-1 min-w-0">
                        <div className="flex items-center gap-3 mb-2">
                          <button
                            onClick={() => setExpandedGroup(isExpanded ? null : group.id)}
                            className="p-2 rounded-md bg-primary/10 text-primary hover:bg-primary/20 transition-colors"
                          >
                            {isExpanded ? <ChevronDown size={20} /> : <ChevronRight size={20} />}
                          </button>
                          <div className="p-2 rounded-md bg-primary/10 text-primary">
                            <Network size={20} />
                          </div>
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-3 mb-1">
                              <span className="text-white font-mono text-sm font-medium">
                                {group.group_name}
                              </span>
                            </div>
                            <div className="flex items-center gap-4 text-xs text-text-secondary">
                              {target && (
                                <div className="flex items-center gap-1">
                                  <span className="font-medium">Target:</span>
                                  <span className="font-mono truncate max-w-[300px]" title={target.iqn}>
                                    {target.alias || target.iqn.split(':').pop()}
                                  </span>
                                </div>
                              )}
                              <div className="flex items-center gap-1">
                                <span className="font-medium">Initiators:</span>
                                <span className="text-white/90">
                                  {group.initiators?.length || 0}
                                </span>
                              </div>
                              <div className="flex items-center gap-1">
                                <span className="font-medium">Created:</span>
                                <span>{new Date(group.created_at).toLocaleDateString()}</span>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div className="flex items-center gap-2">
                        <button
                          onClick={() => setEditingGroup(group)}
                          className="p-2 hover:bg-white/10 rounded-lg text-text-secondary hover:text-white transition-colors"
                          title="Edit group name"
                        >
                          <Settings size={16} />
                        </button>
                        <button
                          onClick={() => handleDelete(group)}
                          disabled={deleteMutation.isPending}
                          className="p-2 hover:bg-red-500/10 rounded-lg text-text-secondary hover:text-red-400 transition-colors disabled:opacity-50"
                          title="Delete group"
                        >
                          <Trash2 size={16} />
                        </button>
                      </div>
                    </div>
                  </div>
                  
                  {/* Expanded view with initiators list */}
                  {isExpanded && (
                    <div className="px-4 pb-4 bg-[#0f161d] border-t border-border-dark">
                      <div className="flex items-center justify-between mb-3 mt-3">
                        <h4 className="text-white text-sm font-semibold">Group Members</h4>
                        <Button
                          size="sm"
                          onClick={() => setShowAddInitiatorModal(group.id)}
                          variant="outline"
                        >
                          <Plus size={14} className="mr-1" />
                          Add Initiator
                        </Button>
                      </div>
                      {group.initiators && group.initiators.length > 0 ? (
                        <div className="space-y-2">
                          {group.initiators.map((initiator) => (
                            <div
                              key={initiator.id}
                              className="flex items-center justify-between p-3 bg-[#141d26] border border-border-dark rounded-lg"
                            >
                              <div className="flex items-center gap-3 flex-1 min-w-0">
                                <div className="p-1.5 rounded bg-primary/10 text-primary">
                                  <Network size={14} />
                                </div>
                                <div className="flex-1 min-w-0">
                                  <div className="flex items-center gap-2">
                                    <span className="text-white font-mono text-xs truncate">
                                      {initiator.iqn}
                                    </span>
                                    <span className={`px-1.5 py-0.5 rounded text-[10px] font-bold uppercase ${
                                      initiator.is_active
                                        ? 'bg-green-500/20 text-green-400'
                                        : 'bg-red-500/20 text-red-400'
                                    }`}>
                                      {initiator.is_active ? 'Active' : 'Inactive'}
                                    </span>
                                  </div>
                                </div>
                              </div>
                              <div className="flex items-center gap-2">
                                <button
                                  onClick={() => {
                                    navigator.clipboard.writeText(initiator.iqn)
                                  }}
                                  className="p-1.5 hover:bg-white/10 rounded text-text-secondary hover:text-white transition-colors"
                                  title="Copy IQN"
                                >
                                  <Copy size={14} />
                                </button>
                                <button
                                  onClick={() => {
                                    if (confirm(`Remove initiator "${initiator.iqn}" from this group?`)) {
                                      removeInitiatorMutation.mutate(initiator.id)
                                    }
                                  }}
                                  disabled={removeInitiatorMutation.isPending}
                                  className="p-1.5 hover:bg-red-500/10 rounded text-text-secondary hover:text-red-400 transition-colors disabled:opacity-50"
                                  title="Remove initiator"
                                >
                                  <Trash2 size={14} />
                                </button>
                              </div>
                            </div>
                          ))}
                        </div>
                      ) : (
                        <div className="p-6 text-center border border-border-dark rounded-lg bg-[#141d26]">
                          <p className="text-text-secondary text-sm mb-2">No initiators in this group</p>
                          <Button
                            size="sm"
                            onClick={() => setShowAddInitiatorModal(group.id)}
                            variant="outline"
                          >
                            <Plus size={14} className="mr-1" />
                            Add First Initiator
                          </Button>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              )
            })}
          </div>
        </div>
      ) : (
        <div className="p-12 text-center">
          <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-border-dark/50 mb-4">
            <Network className="text-text-secondary" size={32} />
          </div>
          <p className="text-white font-medium mb-1">No groups found</p>
          <p className="text-text-secondary text-sm">
            {searchQuery
              ? 'Try adjusting your search criteria'
              : 'Create an initiator group to organize initiators by access control'}
          </p>
        </div>
      )}

      {/* Create Group Modal */}
      {showCreateModal && (
        <CreateGroupModal
          targets={targets}
          onClose={() => setShowCreateModal(false)}
          isLoading={createMutation.isPending}
          onSubmit={(data) => createMutation.mutate(data)}
        />
      )}

      {/* Edit Group Modal */}
      {editingGroup && (
        <EditGroupModal
          group={editingGroup}
          onClose={() => setEditingGroup(null)}
          isLoading={updateMutation.isPending}
          onSubmit={(data) => updateMutation.mutate({ id: editingGroup.id, data })}
        />
      )}

      {/* Add Initiator Modal */}
      {showAddInitiatorModal && (
        <AddInitiatorToGroupModal
          groupName={groups.find(g => g.id === showAddInitiatorModal)?.group_name || ''}
          onClose={() => setShowAddInitiatorModal(null)}
          isLoading={addInitiatorMutation.isPending}
          onSubmit={(initiatorIQN) => addInitiatorMutation.mutate({ groupId: showAddInitiatorModal, initiatorIQN })}
        />
      )}
    </div>
  )
}

function CreateGroupModal({ targets, onClose, isLoading, onSubmit }: {
  targets: SCSTTarget[]
  onClose: () => void
  isLoading: boolean
  onSubmit: (data: { target_id: string; group_name: string }) => void
}) {
  const [targetId, setTargetId] = useState('')
  const [groupName, setGroupName] = useState('')

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!targetId || !groupName.trim()) {
      alert('Please fill in all required fields')
      return
    }
    onSubmit({ target_id: targetId, group_name: groupName.trim() })
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-[#141d26] border border-border-dark rounded-lg p-6 w-full max-w-md">
        <div className="flex items-center justify-between mb-6">
          <h3 className="text-white text-lg font-bold">Create Initiator Group</h3>
          <button onClick={onClose} className="text-text-secondary hover:text-white">
            <X size={20} />
          </button>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">
                Target *
              </label>
              <select
                value={targetId}
                onChange={(e) => setTargetId(e.target.value)}
                className="w-full px-3 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                required
              >
                <option value="">Select a target</option>
                {targets.map(target => (
                  <option key={target.id} value={target.id} className="bg-[#0f161d] text-white">
                    {target.alias || target.iqn.split(':').pop()} ({target.iqn})
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">
                Group Name *
              </label>
              <input
                type="text"
                value={groupName}
                onChange={(e) => setGroupName(e.target.value)}
                placeholder="my-acl-group"
                className="w-full px-3 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                required
              />
              <p className="text-xs text-text-secondary mt-1">
                Group name will be used as ACL group name in SCST
              </p>
            </div>
          </div>
          <div className="flex items-center justify-end gap-3 mt-6">
            <Button type="button" variant="outline" onClick={onClose} disabled={isLoading}>
              Cancel
            </Button>
            <Button type="submit" disabled={isLoading}>
              {isLoading ? 'Creating...' : 'Create'}
            </Button>
          </div>
        </form>
      </div>
    </div>
  )
}

function EditGroupModal({ group, onClose, isLoading, onSubmit }: {
  group: SCSTInitiatorGroup
  onClose: () => void
  isLoading: boolean
  onSubmit: (data: { group_name: string }) => void
}) {
  const [groupName, setGroupName] = useState(group.group_name)

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!groupName.trim()) {
      alert('Group name cannot be empty')
      return
    }
    onSubmit({ group_name: groupName.trim() })
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-[#141d26] border border-border-dark rounded-lg p-6 w-full max-w-md">
        <div className="flex items-center justify-between mb-6">
          <h3 className="text-white text-lg font-bold">Edit Initiator Group</h3>
          <button onClick={onClose} className="text-text-secondary hover:text-white">
            <X size={20} />
          </button>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">
                Group Name *
              </label>
              <input
                type="text"
                value={groupName}
                onChange={(e) => setGroupName(e.target.value)}
                placeholder="my-acl-group"
                className="w-full px-3 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary"
                required
              />
              <p className="text-xs text-text-secondary mt-1">
                Changing the group name will recreate it in SCST
              </p>
            </div>
          </div>
          <div className="flex items-center justify-end gap-3 mt-6">
            <Button type="button" variant="outline" onClick={onClose} disabled={isLoading}>
              Cancel
            </Button>
            <Button type="submit" disabled={isLoading}>
              {isLoading ? 'Updating...' : 'Update'}
            </Button>
          </div>
        </form>
      </div>
    </div>
  )
}

function AddInitiatorToGroupModal({ groupName, onClose, isLoading, onSubmit }: {
  groupName: string
  onClose: () => void
  isLoading: boolean
  onSubmit: (initiatorIQN: string) => void
}) {
  const [initiatorIQN, setInitiatorIQN] = useState('')

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!initiatorIQN.trim()) {
      alert('Please enter an initiator IQN')
      return
    }
    // Validate IQN format (basic check)
    if (!initiatorIQN.trim().toLowerCase().startsWith('iqn.')) {
      alert('Invalid IQN format. IQN must start with "iqn."')
      return
    }
    onSubmit(initiatorIQN.trim())
  }

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-[#141d26] border border-border-dark rounded-lg p-6 w-full max-w-md">
        <div className="flex items-center justify-between mb-6">
          <h3 className="text-white text-lg font-bold">Add Initiator to Group</h3>
          <button onClick={onClose} className="text-text-secondary hover:text-white">
            <X size={20} />
          </button>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">
                Group
              </label>
              <input
                type="text"
                value={groupName}
                disabled
                className="w-full px-3 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white/60 text-sm cursor-not-allowed"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-text-secondary mb-2">
                Initiator IQN *
              </label>
              <input
                type="text"
                value={initiatorIQN}
                onChange={(e) => setInitiatorIQN(e.target.value)}
                placeholder="iqn.1993-08.org.debian:01:example"
                className="w-full px-3 py-2 bg-[#0f161d] border border-border-dark rounded-lg text-white text-sm focus:outline-none focus:border-primary focus:ring-1 focus:ring-primary font-mono"
                required
              />
              <p className="text-xs text-text-secondary mt-1">
                Enter the IQN of the initiator to add to this group
              </p>
            </div>
          </div>
          <div className="flex items-center justify-end gap-3 mt-6">
            <Button type="button" variant="outline" onClick={onClose} disabled={isLoading}>
              Cancel
            </Button>
            <Button type="submit" disabled={isLoading}>
              {isLoading ? 'Adding...' : 'Add Initiator'}
            </Button>
          </div>
        </form>
      </div>
    </div>
  )
}

// Config Editor Tab Component
function ConfigEditorTab() {
  const [content, setContent] = useState('')
  const [isLoading, setIsLoading] = useState(true)
  const [hasChanges, setHasChanges] = useState(false)
  const [originalContent, setOriginalContent] = useState('')
  const [configPath, setConfigPath] = useState('/etc/scst.conf')
  const textareaRef = useRef<HTMLTextAreaElement>(null)

  const { data: configData, refetch: refetchConfig, isFetching } = useQuery<{ content: string; path: string }>({
    queryKey: ['scst-config-file'],
    queryFn: () => scstAPI.getConfigFile(),
  })

  // Handle config data changes
  useEffect(() => {
    if (configData) {
      setContent(configData.content)
      setOriginalContent(configData.content)
      setConfigPath(configData.path)
      setHasChanges(false)
      setIsLoading(false)
    }
  }, [configData])

  // Handle loading state
  useEffect(() => {
    if (isFetching) {
      setIsLoading(true)
    } else if (configData) {
      setIsLoading(false)
    }
  }, [isFetching, configData])

  const saveMutation = useMutation({
    mutationFn: (content: string) => scstAPI.updateConfigFile(content),
    onSuccess: () => {
      setOriginalContent(content)
      setHasChanges(false)
      alert('Configuration file saved successfully!')
    },
    onError: (error: any) => {
      alert(`Failed to save configuration: ${error.response?.data?.error || error.message}`)
    },
  })

  const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setContent(e.target.value)
    setHasChanges(e.target.value !== originalContent)
  }

  const handleSave = () => {
    if (!hasChanges) return
    if (confirm('Save changes to scst.conf? This will update the SCST configuration.')) {
      saveMutation.mutate(content)
    }
  }

  const handleReload = () => {
    if (hasChanges && !confirm('You have unsaved changes. Reload anyway?')) {
      return
    }
    setIsLoading(true)
    refetchConfig()
  }

  useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.focus()
    }
  }, [])

  return (
    <div className="flex flex-col h-full min-h-[600px] bg-[#0a0f14] border border-border-dark rounded-lg overflow-hidden">
      {/* Header */}
      <div className="flex-none px-6 py-4 border-b border-border-dark bg-[#141d26] flex items-center justify-between">
        <div className="flex items-center gap-3">
          <Terminal className="text-primary" size={20} />
          <div>
            <h3 className="text-white font-bold text-sm">SCST Configuration Editor</h3>
            <p className="text-text-secondary text-xs mt-0.5">
              Edit /etc/scst.conf file directly
            </p>
          </div>
        </div>
        <div className="flex items-center gap-2">
          <Button
            variant="outline"
            size="sm"
            onClick={handleReload}
            disabled={isLoading}
            className="flex items-center gap-2"
          >
            <RefreshCw size={16} className={isLoading ? 'animate-spin' : ''} />
            <span>Reload</span>
          </Button>
          <Button
            size="sm"
            onClick={handleSave}
            disabled={!hasChanges || saveMutation.isPending}
            className="flex items-center gap-2 bg-primary hover:bg-blue-600"
          >
            <Save size={16} />
            <span>{saveMutation.isPending ? 'Saving...' : 'Save'}</span>
          </Button>
        </div>
      </div>

      {/* Editor */}
      <div className="flex-1 relative overflow-hidden">
        {isLoading ? (
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="text-text-secondary">
              <RefreshCw size={24} className="animate-spin mx-auto mb-2" />
              <p>Loading configuration...</p>
            </div>
          </div>
        ) : (
          <textarea
            ref={textareaRef}
            value={content}
            onChange={handleContentChange}
            className="w-full h-full p-4 bg-[#0a0f14] text-green-400 font-mono text-sm resize-none focus:outline-none focus:ring-0 border-0"
            style={{
              fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',
              lineHeight: '1.6',
              tabSize: 2,
            }}
            spellCheck={false}
            placeholder="Loading configuration file..."
          />
        )}
      </div>

      {/* Footer */}
      <div className="flex-none px-6 py-3 border-t border-border-dark bg-[#141d26] flex items-center justify-between text-xs">
        <div className="flex items-center gap-4 text-text-secondary">
          <span>Path: {configPath}</span>
          {hasChanges && (
            <span className="text-yellow-400 flex items-center gap-1">
              <span className="w-2 h-2 bg-yellow-400 rounded-full"></span>
              Unsaved changes
            </span>
          )}
        </div>
        <div className="text-text-secondary">
          {content.split('\n').length} lines
        </div>
      </div>
    </div>
  )
}
