import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { formatBytes } from '@/lib/format'
import { objectStorageApi, PoolDatasetInfo, CurrentSetup, Object } from '@/api/objectStorage'
import UsersAndKeys from './UsersAndKeys'
import { systemAPI } from '@/api/system'
import {
  Folder,
  Share2,
  Globe,
  Search,
  Plus,
  CheckCircle2,
  HardDrive,
  Database,
  Clock,
  Link as LinkIcon,
  Copy,
  FileText,
  Settings,
  Users,
  Activity,
  Filter,
  RefreshCw,
  Trash2,
  AlertCircle,
  FolderOpen,
  File,
  ChevronRight,
  ArrowLeft
} from 'lucide-react'

const S3_PORT = 9000

export default function ObjectStorage() {
  const [activeTab, setActiveTab] = useState<'buckets' | 'browse' | 'users' | 'monitoring' | 'settings'>('buckets')
  const [searchQuery, setSearchQuery] = useState('')
  const [currentPage, setCurrentPage] = useState(1)
  const [showSetupModal, setShowSetupModal] = useState(false)
  const [selectedPool, setSelectedPool] = useState<string>('')
  const [selectedDataset, setSelectedDataset] = useState<string>('')
  const [createNewDataset, setCreateNewDataset] = useState(false)
  const [newDatasetName, setNewDatasetName] = useState('')
  const [isRefreshingBuckets, setIsRefreshingBuckets] = useState(false)
  const [showCreateBucketModal, setShowCreateBucketModal] = useState(false)
  const [newBucketName, setNewBucketName] = useState('')
  const [deleteConfirmBucket, setDeleteConfirmBucket] = useState<string | null>(null)
  const itemsPerPage = 10
  const queryClient = useQueryClient()

  // Fetch management IP address
  const { data: managementIP = 'localhost' } = useQuery<string>({
    queryKey: ['system-management-ip'],
    queryFn: systemAPI.getManagementIPAddress,
    staleTime: 5 * 60 * 1000, // Cache for 5 minutes
    retry: 2,
  })

  // Construct S3 endpoint with management IP
  const S3_ENDPOINT = `http://${managementIP}:${S3_PORT}`

  // Fetch buckets from API
  const { data: buckets = [], isLoading: bucketsLoading } = useQuery({
    queryKey: ['object-storage-buckets'],
    queryFn: objectStorageApi.listBuckets,
    refetchInterval: 5000, // Auto-refresh every 5 seconds
    staleTime: 0,
  })

  // Fetch available datasets for setup
  const { data: availableDatasets = [] } = useQuery<PoolDatasetInfo[]>({
    queryKey: ['object-storage-setup-datasets'],
    queryFn: objectStorageApi.getAvailableDatasets,
    enabled: showSetupModal, // Only fetch when modal is open
  })

  // Fetch current setup
  const { data: currentSetup } = useQuery<CurrentSetup | null>({
    queryKey: ['object-storage-current-setup'],
    queryFn: objectStorageApi.getCurrentSetup,
  })

  // Setup mutation
  const setupMutation = useMutation({
    mutationFn: ({ poolName, datasetName, createNew }: { poolName: string; datasetName: string; createNew: boolean }) =>
      currentSetup
        ? objectStorageApi.updateObjectStorage(poolName, datasetName, createNew)
        : objectStorageApi.setupObjectStorage(poolName, datasetName, createNew),
    onSuccess: (data) => {
      queryClient.invalidateQueries({ queryKey: ['object-storage-current-setup'] })
      queryClient.invalidateQueries({ queryKey: ['object-storage-buckets'] })
      setShowSetupModal(false)
      if (currentSetup) {
        alert(`Object storage dataset updated successfully!\n\n${data.message}\n\n⚠️ IMPORTANT: Existing data in the previous dataset is NOT automatically migrated. You may need to manually migrate data or restart MinIO service to use the new dataset.`)
      } else {
        alert('Object storage setup completed successfully!')
      }
    },
    onError: (error: any) => {
      alert(error.response?.data?.error || `Failed to ${currentSetup ? 'update' : 'setup'} object storage`)
    },
  })

  // Create bucket mutation with optimistic update
  const createBucketMutation = useMutation({
    mutationFn: (name: string) => objectStorageApi.createBucket(name),
    onMutate: async (name: string) => {
      await queryClient.cancelQueries({ queryKey: ['object-storage-buckets'] })
      const previousBuckets = queryClient.getQueryData(['object-storage-buckets'])
      queryClient.setQueryData(['object-storage-buckets'], (old: any[] = []) => {
        const newBucket = {
          name,
          creation_date: new Date().toISOString(),
          size: 0,
          objects: 0,
          access_policy: 'private',
        }
        return [...old, newBucket]
      })
      setShowCreateBucketModal(false)
      setNewBucketName('')
      return { previousBuckets }
    },
    onError: (error: any, _name: string, context: any) => {
      if (context?.previousBuckets) {
        queryClient.setQueryData(['object-storage-buckets'], context.previousBuckets)
      }
      setShowCreateBucketModal(true) // Reopen modal on error
      alert(error.response?.data?.error || 'Failed to create bucket')
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['object-storage-buckets'] })
      alert('Bucket created successfully!')
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['object-storage-buckets'] })
    },
  })

  // Delete bucket mutation
  const deleteBucketMutation = useMutation({
    mutationFn: (name: string) => objectStorageApi.deleteBucket(name),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['object-storage-buckets'] })
      setDeleteConfirmBucket(null)
      alert('Bucket deleted successfully!')
    },
    onError: (error: any) => {
      alert(error.response?.data?.error || 'Failed to delete bucket')
    },
  })

  // Transform buckets data
  const transformedBuckets = buckets.map((bucket) => ({
    ...bucket,
    usage: bucket.size || 0,
    objects: bucket.objects || 0,
    accessPolicy: bucket.access_policy || 'private',
  }))

  // Filter buckets
  const filteredBuckets = transformedBuckets.filter((bucket) =>
    bucket.name.toLowerCase().includes(searchQuery.toLowerCase())
  )

  // Pagination
  const totalPages = Math.ceil(filteredBuckets.length / itemsPerPage)
  const paginatedBuckets = filteredBuckets.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  )

  // Calculate totals
  const totalUsage = transformedBuckets.reduce((sum, b) => sum + b.usage, 0)
  const totalObjects = transformedBuckets.reduce((sum, b) => sum + b.objects, 0)

  // Get bucket icon
  const getBucketIcon = (bucket: typeof transformedBuckets[0]) => {
    if (bucket.accessPolicy === 'public-read' || bucket.accessPolicy === 'public-read-write') {
      return <Globe className="text-orange-500" size={20} />
    }
    return <Share2 className="text-purple-500" size={20} />
  }

  // Get access policy badge
  const getAccessPolicyBadge = (policy: string) => {
    if (policy === 'public-read-write') {
      return (
        <span className="inline-flex items-center rounded-full bg-red-500/10 px-2.5 py-0.5 text-xs font-medium text-red-500 border border-red-500/20">
          Public Read/Write
        </span>
      )
    }
    if (policy === 'public-read') {
      return (
        <span className="inline-flex items-center rounded-full bg-orange-500/10 px-2.5 py-0.5 text-xs font-medium text-orange-500 border border-orange-500/20">
          Public Read
        </span>
      )
    }
    return (
      <span className="inline-flex items-center rounded-full bg-green-500/10 px-2.5 py-0.5 text-xs font-medium text-green-500 border border-green-500/20">
        Private
      </span>
    )
  }

  // Format date
  const formatDate = (dateString: string) => {
    const date = new Date(dateString)
    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
  }

  // Copy to clipboard helper
  const copyToClipboard = async (text: string, label: string) => {
    try {
      await navigator.clipboard.writeText(text)
      alert(`${label} copied to clipboard!`)
    } catch (error) {
      console.error(`Failed to copy ${label}:`, error)
      // Fallback: select text
      const textArea = document.createElement('textarea')
      textArea.value = text
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      document.body.appendChild(textArea)
      textArea.select()
      try {
        document.execCommand('copy')
        alert(`${label} copied to clipboard!`)
      } catch (err) {
        alert(`Failed to copy. ${label}: ${text}`)
      }
      document.body.removeChild(textArea)
    }
  }

  return (
    <div className="flex flex-col h-full bg-[#0f1720]">
      {/* Main Content */}
      <main className="flex-1 flex flex-col overflow-y-auto relative scroll-smooth">
        <div className="flex flex-col max-w-[1200px] w-full mx-auto p-6 md:p-8 lg:p-12 gap-8">
          {/* Page Heading */}
          <div className="flex flex-wrap justify-between items-start gap-4">
            <div className="flex flex-col gap-2">
              <h1 className="text-white tracking-tight text-[32px] font-bold leading-tight">
                Object Storage Service
              </h1>
              <p className="text-text-secondary text-sm font-normal max-w-xl">
                Manage S3-compatible buckets, configure access policies, and monitor real-time object storage performance.
              </p>
            </div>
            <div className="flex gap-3">
              <button
                onClick={async () => {
                  setIsRefreshingBuckets(true)
                  try {
                    await queryClient.invalidateQueries({ queryKey: ['object-storage-buckets'] })
                    await queryClient.refetchQueries({ queryKey: ['object-storage-buckets'] })
                    // Small delay to show feedback
                    await new Promise(resolve => setTimeout(resolve, 300))
                    alert('Buckets refreshed successfully!')
                  } catch (error) {
                    console.error('Failed to refresh buckets:', error)
                    alert('Failed to refresh buckets. Please try again.')
                  } finally {
                    setIsRefreshingBuckets(false)
                  }
                }}
                disabled={bucketsLoading || isRefreshingBuckets}
                className="flex h-10 items-center justify-center rounded-lg border border-border-dark px-4 text-white text-sm font-medium hover:bg-[#233648] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                title="Refresh buckets list"
              >
                <RefreshCw className={`mr-2 ${isRefreshingBuckets ? 'animate-spin' : ''}`} size={20} />
                {isRefreshingBuckets ? 'Refreshing...' : 'Refresh Buckets'}
              </button>
              {!currentSetup ? (
                <button
                  onClick={() => setShowSetupModal(true)}
                  className="flex h-10 items-center justify-center rounded-lg bg-primary px-4 text-white text-sm font-medium hover:bg-blue-600 transition-colors"
                >
                  <Plus className="mr-2" size={20} />
                  Setup Object Storage
                </button>
              ) : (
                <button
                  onClick={() => setShowSetupModal(true)}
                  className="flex h-10 items-center justify-center rounded-lg bg-orange-500 px-4 text-white text-sm font-medium hover:bg-orange-600 transition-colors"
                >
                  <Settings className="mr-2" size={20} />
                  Change Dataset
                </button>
              )}
              <button className="flex h-10 items-center justify-center rounded-lg border border-border-dark px-4 text-white text-sm font-medium hover:bg-[#233648] transition-colors">
                <FileText className="mr-2" size={20} />
                Documentation
              </button>
              <button className="flex h-10 items-center justify-center rounded-lg bg-[#233648] px-4 text-white text-sm font-medium hover:bg-[#2b4055] transition-colors border border-border-dark">
                <Settings className="mr-2" size={20} />
                Config
              </button>
            </div>
          </div>

          {/* Stats Cards */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {/* Service Status */}
            <div className="flex flex-col gap-2 rounded-lg p-5 border border-border-dark bg-[#1c2936]">
              <div className="flex items-center justify-between">
                <p className="text-text-secondary text-sm font-medium">Service Status</p>
                <CheckCircle2 className="text-[#0bda5b]" size={20} />
              </div>
              <p className="text-white tracking-tight text-2xl font-bold">Running</p>
              <p className="text-text-secondary text-xs">Port 9000 (TLS Enabled)</p>
            </div>

            {/* Total Usage */}
            <div className="flex flex-col gap-2 rounded-lg p-5 border border-border-dark bg-[#1c2936]">
              <div className="flex items-center justify-between">
                <p className="text-text-secondary text-sm font-medium">Total Usage</p>
                <HardDrive className="text-primary" size={20} />
              </div>
              <div className="flex items-baseline gap-2">
                <p className="text-white tracking-tight text-2xl font-bold">{formatBytes(totalUsage, 1)}</p>
                <p className="text-[#0bda5b] text-sm font-medium">+2.1%</p>
              </div>
              <div className="w-full bg-[#233648] rounded-full h-1.5 mt-1">
                <div className="bg-primary h-1.5 rounded-full" style={{ width: '45%' }}></div>
              </div>
            </div>

            {/* Object Count */}
            <div className="flex flex-col gap-2 rounded-lg p-5 border border-border-dark bg-[#1c2936]">
              <div className="flex items-center justify-between">
                <p className="text-text-secondary text-sm font-medium">Object Count</p>
                <Database className="text-blue-400" size={20} />
              </div>
              <div className="flex items-baseline gap-2">
                <p className="text-white tracking-tight text-2xl font-bold">
                  {(totalObjects / 1000000).toFixed(1)}M
                </p>
                <p className="text-[#0bda5b] text-sm font-medium">+0.5%</p>
              </div>
              <p className="text-text-secondary text-xs">Total objects across all buckets</p>
            </div>

            {/* Uptime */}
            <div className="flex flex-col gap-2 rounded-lg p-5 border border-border-dark bg-[#1c2936]">
              <div className="flex items-center justify-between">
                <p className="text-text-secondary text-sm font-medium">Uptime</p>
                <Clock className="text-green-400" size={20} />
              </div>
              <p className="text-white tracking-tight text-2xl font-bold">99.9%</p>
              <p className="text-text-secondary text-xs">Last 30 days</p>
            </div>
          </div>

          {/* Tabs Header */}
          <div className="border-b border-border-dark">
            <div className="flex gap-8 px-2">
              <button
                onClick={() => setActiveTab('buckets')}
                className={`flex items-center gap-2 border-b-2 pb-3 pt-2 transition-colors ${
                  activeTab === 'buckets'
                    ? 'border-primary text-white'
                    : 'border-transparent text-text-secondary hover:text-white'
                }`}
              >
                <Folder size={20} />
                <span className="text-sm font-bold">Buckets</span>
              </button>
              <button
                onClick={() => setActiveTab('browse')}
                className={`flex items-center gap-2 border-b-2 pb-3 pt-2 transition-colors ${
                  activeTab === 'browse'
                    ? 'border-primary text-white'
                    : 'border-transparent text-text-secondary hover:text-white'
                }`}
              >
                <FolderOpen size={20} />
                <span className="text-sm font-bold">Browse</span>
              </button>
              <button
                onClick={() => setActiveTab('users')}
                className={`flex items-center gap-2 border-b-2 pb-3 pt-2 transition-colors ${
                  activeTab === 'users'
                    ? 'border-primary text-white'
                    : 'border-transparent text-text-secondary hover:text-white'
                }`}
              >
                <Users size={20} />
                <span className="text-sm font-bold">Users & Keys</span>
              </button>
              <button
                onClick={() => setActiveTab('monitoring')}
                className={`flex items-center gap-2 border-b-2 pb-3 pt-2 transition-colors ${
                  activeTab === 'monitoring'
                    ? 'border-primary text-white'
                    : 'border-transparent text-text-secondary hover:text-white'
                }`}
              >
                <Activity size={20} />
                <span className="text-sm font-bold">Monitoring</span>
              </button>
              <button
                onClick={() => setActiveTab('settings')}
                className={`flex items-center gap-2 border-b-2 pb-3 pt-2 transition-colors ${
                  activeTab === 'settings'
                    ? 'border-primary text-white'
                    : 'border-transparent text-text-secondary hover:text-white'
                }`}
              >
                <Filter size={20} />
                <span className="text-sm font-bold">Settings</span>
              </button>
            </div>
          </div>

          {/* Tab Content */}
          {activeTab === 'browse' && <BucketBrowser S3_ENDPOINT={S3_ENDPOINT} />}
          {activeTab === 'buckets' && (
            <>
              {/* Buckets Section */}
              <div className="flex flex-col gap-6">
                {/* Search and Create */}
                <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
                  <div className="relative flex-1 max-w-md">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-text-secondary" size={18} />
                    <input
                      type="text"
                      placeholder="Filter buckets..."
                      value={searchQuery}
                      onChange={(e) => {
                        setSearchQuery(e.target.value)
                        setCurrentPage(1) // Reset to first page on search
                      }}
                      className="w-full pl-10 pr-4 py-2 bg-[#1c2936] border border-border-dark rounded-lg text-white placeholder-text-secondary focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
                    />
                  </div>
                  <button
                    onClick={() => setShowCreateBucketModal(true)}
                    className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors font-medium"
                  >
                    <Plus size={18} />
                    Create Bucket
                  </button>
                </div>

                {/* Buckets Table */}
                <div className="rounded-lg border border-border-dark bg-[#1c2936] overflow-hidden">
                  <div className="overflow-x-auto">
                    <table className="w-full">
                      <thead className="bg-[#233648] border-b border-border-dark">
                        <tr>
                          <th className="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
                            Name
                          </th>
                          <th className="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
                            Usage
                          </th>
                          <th className="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
                            Objects
                          </th>
                          <th className="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
                            Access Policy
                          </th>
                          <th className="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
                            Created
                          </th>
                          <th className="px-6 py-3 text-right text-xs font-medium text-text-secondary uppercase tracking-wider">
                            Actions
                          </th>
                        </tr>
                      </thead>
                      <tbody className="divide-y divide-border-dark">
                        {bucketsLoading ? (
                          <tr>
                            <td colSpan={6} className="px-6 py-8 text-center text-text-secondary">
                              Loading buckets...
                            </td>
                          </tr>
                        ) : paginatedBuckets.length === 0 ? (
                          <tr>
                            <td colSpan={6} className="px-6 py-8 text-center text-text-secondary">
                              {searchQuery ? 'No buckets found matching your search.' : 'No buckets yet. Create your first bucket to get started.'}
                            </td>
                          </tr>
                        ) : (
                          paginatedBuckets.map((bucket) => (
                            <tr key={bucket.name} className="hover:bg-[#233648] transition-colors">
                              <td className="px-6 py-4">
                                <div className="flex items-center gap-3">
                                  {getBucketIcon(bucket)}
                                  <div className="flex flex-col">
                                    <span className="text-white font-medium">{bucket.name}</span>
                                    <span className="text-text-secondary text-xs">standard</span>
                                  </div>
                                </div>
                              </td>
                              <td className="px-6 py-4 text-white">{formatBytes(bucket.usage, 1)}</td>
                              <td className="px-6 py-4 text-white">{bucket.objects}</td>
                              <td className="px-6 py-4">{getAccessPolicyBadge(bucket.accessPolicy)}</td>
                              <td className="px-6 py-4 text-text-secondary">{formatDate(bucket.creation_date)}</td>
                              <td className="px-6 py-4 whitespace-nowrap text-right">
                                <div className="flex items-center justify-end gap-2">
                                  <button
                                    onClick={() => copyToClipboard(bucket.name, 'Bucket Name')}
                                    className="px-3 py-1.5 text-xs font-medium text-white bg-[#233648] hover:bg-[#2b4055] border border-border-dark rounded-lg transition-colors flex items-center gap-1.5"
                                    title="Copy Bucket Name"
                                  >
                                    <Copy size={14} />
                                    Copy Name
                                  </button>
                                  <button
                                    onClick={() => copyToClipboard(`${S3_ENDPOINT}/${bucket.name}`, 'Bucket Endpoint')}
                                    className="px-3 py-1.5 text-xs font-medium text-white bg-[#233648] hover:bg-[#2b4055] border border-border-dark rounded-lg transition-colors flex items-center gap-1.5"
                                    title="Copy Bucket Endpoint"
                                  >
                                    <LinkIcon size={14} />
                                    Copy Endpoint
                                  </button>
                                  <button
                                    onClick={() => setDeleteConfirmBucket(bucket.name)}
                                    disabled={deleteBucketMutation.isPending}
                                    className="px-3 py-1.5 text-xs font-medium text-red-400 hover:bg-red-500/10 border border-red-500/20 rounded-lg transition-colors flex items-center gap-1.5 disabled:opacity-50"
                                    title="Delete Bucket"
                                  >
                                    <Trash2 size={14} />
                                    {deleteBucketMutation.isPending ? 'Deleting...' : 'Delete'}
                                  </button>
                                </div>
                              </td>
                            </tr>
                          ))
                        )}
                      </tbody>
                    </table>
                  </div>
                  {/* Pagination */}
                  {totalPages > 1 && (
                    <div className="px-6 py-4 border-t border-border-dark flex items-center justify-between">
                      <div className="text-sm text-text-secondary">
                        Showing {(currentPage - 1) * itemsPerPage + 1} to {Math.min(currentPage * itemsPerPage, filteredBuckets.length)} of {filteredBuckets.length} buckets
                      </div>
                      <div className="flex gap-2">
                        <button
                          onClick={() => setCurrentPage((prev) => Math.max(1, prev - 1))}
                          disabled={currentPage === 1}
                          className="px-3 py-1.5 text-sm text-white bg-[#233648] hover:bg-[#2b4055] border border-border-dark rounded-lg disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                        >
                          Previous
                        </button>
                        <button
                          onClick={() => setCurrentPage((prev) => Math.min(totalPages, prev + 1))}
                          disabled={currentPage === totalPages}
                          className="px-3 py-1.5 text-sm text-white bg-[#233648] hover:bg-[#2b4055] border border-border-dark rounded-lg disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                        >
                          Next
                        </button>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </>
          )}

          {activeTab === 'users' && <UsersAndKeys S3_ENDPOINT={S3_ENDPOINT} />}

          {activeTab === 'monitoring' && (
            <div className="bg-[#1c2936] border border-border-dark rounded-lg p-8 text-center">
              <Activity className="mx-auto mb-4 text-text-secondary" size={48} />
              <p className="text-text-secondary text-sm">Monitoring dashboard coming soon</p>
            </div>
          )}

          {activeTab === 'settings' && (
            <div className="bg-[#1c2936] border border-border-dark rounded-lg p-8 text-center">
              <Settings className="mx-auto mb-4 text-text-secondary" size={48} />
              <p className="text-text-secondary text-sm">Settings configuration coming soon</p>
            </div>
          )}
        </div>
      </main>

      {/* Create Bucket Modal */}
      {showCreateBucketModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-[#1c2936] border border-border-dark rounded-lg p-6 max-w-md w-full mx-4">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-white text-xl font-bold">Create New Bucket</h2>
              <button
                onClick={() => {
                  setShowCreateBucketModal(false)
                  setNewBucketName('')
                }}
                className="text-text-secondary hover:text-white transition-colors"
              >
                ✕
              </button>
            </div>
            <div className="space-y-4">
              <div>
                <label className="block text-sm font-medium text-white mb-2">Bucket Name</label>
                <input
                  type="text"
                  value={newBucketName}
                  onChange={(e) => setNewBucketName(e.target.value)}
                  placeholder="Enter bucket name"
                  className="w-full px-4 py-2 bg-[#233648] border border-border-dark rounded-lg text-white placeholder-text-secondary focus:outline-none focus:ring-2 focus:ring-primary"
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' && newBucketName.trim()) {
                      createBucketMutation.mutate(newBucketName.trim())
                    }
                  }}
                />
                <p className="mt-1 text-xs text-text-secondary">
                  Bucket names must be unique and follow S3 naming conventions
                </p>
              </div>
              <div className="flex gap-3 justify-end pt-4">
                <button
                  onClick={() => {
                    setShowCreateBucketModal(false)
                    setNewBucketName('')
                  }}
                  className="px-4 py-2 text-white text-sm font-medium rounded-lg border border-border-dark hover:bg-[#233648] transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={() => {
                    if (newBucketName.trim()) {
                      createBucketMutation.mutate(newBucketName.trim())
                    }
                  }}
                  disabled={!newBucketName.trim() || createBucketMutation.isPending}
                  className="px-4 py-2 bg-primary hover:bg-blue-600 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {createBucketMutation.isPending ? 'Creating...' : 'Create Bucket'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Delete Bucket Confirmation Dialog */}
      {deleteConfirmBucket && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-[#1c2936] border border-border-dark rounded-lg p-6 max-w-md w-full mx-4">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-white text-xl font-bold">Confirm Delete Bucket</h2>
              <button
                onClick={() => setDeleteConfirmBucket(null)}
                className="text-text-secondary hover:text-white transition-colors"
              >
                ✕
              </button>
            </div>
            <div className="space-y-4">
              <div className="bg-red-500/10 border border-red-500/20 rounded-lg p-4">
                <div className="flex items-start gap-2">
                  <AlertCircle className="text-red-400 mt-0.5" size={20} />
                  <div>
                    <p className="text-red-400 text-sm font-medium mb-1">Warning</p>
                    <p className="text-red-300 text-xs">
                      This action cannot be undone. All objects within the bucket "{deleteConfirmBucket}" will be permanently deleted.
                    </p>
                  </div>
                </div>
              </div>
              <div className="flex gap-3 justify-end pt-4">
                <button
                  onClick={() => setDeleteConfirmBucket(null)}
                  className="px-4 py-2 text-white text-sm font-medium rounded-lg border border-border-dark hover:bg-[#233648] transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={() => {
                    deleteBucketMutation.mutate(deleteConfirmBucket)
                    setDeleteConfirmBucket(null)
                  }}
                  disabled={deleteBucketMutation.isPending}
                  className="px-4 py-2 bg-red-600 hover:bg-red-700 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {deleteBucketMutation.isPending ? 'Deleting...' : 'Delete Bucket'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Setup Modal */}
      {showSetupModal && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
          <div className="bg-[#1c2936] border border-border-dark rounded-lg p-6 max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-white text-xl font-bold">
                {currentSetup ? 'Change Object Storage Dataset' : 'Setup Object Storage'}
              </h2>
              <button
                onClick={() => setShowSetupModal(false)}
                className="text-text-secondary hover:text-white transition-colors"
              >
                ✕
              </button>
            </div>
            <div className="space-y-6">
              <div>
                <label className="block text-sm font-medium text-white mb-2">Select Pool</label>
                <select
                  value={selectedPool}
                  onChange={(e) => {
                    setSelectedPool(e.target.value)
                    setSelectedDataset('')
                  }}
                  className="w-full px-4 py-2 bg-[#233648] border border-border-dark rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary"
                >
                  <option value="">Select a pool...</option>
                  {availableDatasets.map((pool) => (
                    <option key={pool.pool_id} value={pool.pool_id}>
                      {pool.pool_name}
                    </option>
                  ))}
                </select>
              </div>

              {selectedPool && (
                <div>
                  <label className="block text-sm font-medium text-white mb-2">Select Dataset</label>
                  <div className="space-y-2 mb-3">
                    <label className="flex items-center gap-2 cursor-pointer">
                      <input
                        type="radio"
                        checked={!createNewDataset}
                        onChange={() => {
                          setCreateNewDataset(false)
                          setNewDatasetName('')
                        }}
                        className="text-primary"
                      />
                      <span className="text-white text-sm">Use existing dataset</span>
                    </label>
                    <label className="flex items-center gap-2 cursor-pointer">
                      <input
                        type="radio"
                        checked={createNewDataset}
                        onChange={() => setCreateNewDataset(true)}
                        className="text-primary"
                      />
                      <span className="text-white text-sm">Create new dataset</span>
                    </label>
                  </div>

                  {!createNewDataset ? (
                    <select
                      value={selectedDataset}
                      onChange={(e) => setSelectedDataset(e.target.value)}
                      className="w-full px-4 py-2 bg-[#233648] border border-border-dark rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-primary"
                    >
                      <option value="">Select a dataset...</option>
                      {availableDatasets
                        .find((p) => p.pool_id === selectedPool)
                        ?.datasets.map((dataset) => (
                          <option key={dataset.id} value={dataset.name}>
                            {dataset.name} {dataset.mount_point && `(${dataset.mount_point})`}
                          </option>
                        ))}
                    </select>
                  ) : (
                    <input
                      type="text"
                      value={newDatasetName}
                      onChange={(e) => setNewDatasetName(e.target.value)}
                      placeholder="Enter new dataset name"
                      className="w-full px-4 py-2 bg-[#233648] border border-border-dark rounded-lg text-white placeholder-text-secondary focus:outline-none focus:ring-2 focus:ring-primary"
                    />
                  )}
                </div>
              )}

              <div className="flex gap-3 justify-end pt-4">
                <button
                  onClick={() => setShowSetupModal(false)}
                  className="px-4 py-2 text-white text-sm font-medium rounded-lg border border-border-dark hover:bg-[#233648] transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={() => {
                    const pool = availableDatasets.find((p) => p.pool_id === selectedPool)
                    if (!pool) return

                    const datasetName = createNewDataset ? newDatasetName : selectedDataset
                    if (!datasetName.trim()) {
                      alert('Please select or enter a dataset name')
                      return
                    }

                    setupMutation.mutate({
                      poolName: pool.pool_name,
                      datasetName: datasetName.trim(),
                      createNew: createNewDataset,
                    })
                  }}
                  disabled={!selectedPool || (!createNewDataset && !selectedDataset) || (createNewDataset && !newDatasetName.trim()) || setupMutation.isPending}
                  className="px-4 py-2 bg-primary hover:bg-blue-600 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {setupMutation.isPending ? 'Setting up...' : currentSetup ? 'Update Configuration' : 'Setup Object Storage'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

// Bucket Browser Component
function BucketBrowser({ S3_ENDPOINT }: { S3_ENDPOINT: string }) {
  const [selectedBucket, setSelectedBucket] = useState<string | null>(null)
  const [currentPath, setCurrentPath] = useState<string>('')
  const queryClient = useQueryClient()

  // Fetch buckets
  const { data: buckets = [] } = useQuery({
    queryKey: ['object-storage-buckets'],
    queryFn: objectStorageApi.listBuckets,
    refetchInterval: 5000, // Auto-refresh every 5 seconds
    staleTime: 0,
  })

  // Fetch objects in selected bucket
  const { data: objects = [], isLoading: objectsLoading } = useQuery<Object[]>({
    queryKey: ['object-storage-objects', selectedBucket, currentPath],
    queryFn: () => {
      if (!selectedBucket) return Promise.resolve([])
      return objectStorageApi.listObjects(selectedBucket, currentPath || undefined)
    },
    enabled: !!selectedBucket,
    refetchInterval: 5000, // Auto-refresh every 5 seconds
    staleTime: 0,
  })

  const navigateToFolder = (folderKey: string) => {
    setCurrentPath(folderKey)
  }

  const navigateUp = () => {
    if (!currentPath) {
      setSelectedBucket(null)
      return
    }
    // Remove last folder from path
    const parts = currentPath.split('/').filter(p => p)
    if (parts.length > 0) {
      parts.pop()
      setCurrentPath(parts.length > 0 ? parts.join('/') + '/' : '')
    } else {
      setCurrentPath('')
    }
  }

  const getBreadcrumbs = () => {
    const crumbs = [{ name: selectedBucket || '', path: '' }]
    if (currentPath) {
      const parts = currentPath.split('/').filter(p => p)
      let path = ''
      parts.forEach(part => {
        path += part + '/'
        crumbs.push({ name: part, path })
      })
    }
    return crumbs
  }

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

  if (!selectedBucket) {
    return (
      <div className="flex flex-col gap-6">
        <div className="flex items-center justify-between">
          <h2 className="text-white text-xl font-semibold">Select a Bucket to Browse</h2>
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {buckets.map(bucket => (
            <button
              key={bucket.name}
              onClick={() => setSelectedBucket(bucket.name)}
              className="flex flex-col gap-3 p-6 rounded-lg border border-border-dark bg-[#1c2936] hover:bg-[#233648] transition-colors text-left"
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <FolderOpen className="text-primary" size={24} />
                  <span className="text-white font-medium">{bucket.name}</span>
                </div>
                {bucket.access_policy === 'public-read' || bucket.access_policy === 'public-read-write' ? (
                  <Globe className="text-orange-500" size={18} />
                ) : (
                  <Share2 className="text-purple-500" size={18} />
                )}
              </div>
              <div className="flex items-center justify-between text-sm">
                <span className="text-text-secondary">{formatBytes(bucket.size, 1)}</span>
                <span className="text-text-secondary">{bucket.objects} objects</span>
              </div>
            </button>
          ))}
        </div>
        {buckets.length === 0 && (
          <div className="text-center py-12">
            <FolderOpen className="mx-auto text-text-secondary mb-4" size={48} />
            <p className="text-text-secondary">No buckets available</p>
          </div>
        )}
      </div>
    )
  }

  const breadcrumbs = getBreadcrumbs()

  return (
    <div className="flex flex-col gap-6">
      {/* Header with breadcrumbs */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2 flex-wrap">
          <button
            onClick={() => {
              setSelectedBucket(null)
              setCurrentPath('')
            }}
            className="flex items-center gap-2 px-3 py-1.5 text-sm text-text-secondary hover:text-white transition-colors rounded-lg hover:bg-[#233648]"
          >
            <ArrowLeft size={16} />
            Back to Buckets
          </button>
          <ChevronRight className="text-text-secondary" size={16} />
          {breadcrumbs.map((crumb, index) => (
            <div key={index} className="flex items-center gap-2">
              {index > 0 && <ChevronRight className="text-text-secondary" size={16} />}
              <button
                onClick={() => {
                  if (index === 0) {
                    setCurrentPath('')
                  } else {
                    setCurrentPath(crumb.path)
                  }
                }}
                className={`px-3 py-1.5 text-sm rounded-lg transition-colors ${
                  index === breadcrumbs.length - 1
                    ? 'text-white bg-[#233648]'
                    : 'text-text-secondary hover:text-white hover:bg-[#233648]'
                }`}
              >
                {crumb.name || 'root'}
              </button>
            </div>
          ))}
        </div>
        <button
          onClick={() => {
            queryClient.invalidateQueries({ queryKey: ['object-storage-objects', selectedBucket, currentPath] })
          }}
          className="flex items-center gap-2 px-4 py-2 text-sm text-white bg-[#233648] hover:bg-[#2b4055] border border-border-dark rounded-lg transition-colors"
        >
          <RefreshCw size={16} />
          Refresh
        </button>
      </div>

      {/* Objects table */}
      <div className="rounded-lg border border-border-dark bg-[#1c2936] overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead className="bg-[#233648] border-b border-border-dark">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
                  Name
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
                  Size
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
                  Last Modified
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-text-secondary uppercase tracking-wider">
                  Actions
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-border-dark">
              {currentPath && (
                <tr className="hover:bg-[#233648] transition-colors">
                  <td className="px-6 py-4">
                    <button
                      onClick={navigateUp}
                      className="flex items-center gap-2 text-white hover:text-primary transition-colors"
                    >
                      <ArrowLeft size={16} />
                      <span>..</span>
                    </button>
                  </td>
                  <td className="px-6 py-4 text-text-secondary">-</td>
                  <td className="px-6 py-4 text-text-secondary">-</td>
                  <td className="px-6 py-4"></td>
                </tr>
              )}
              {objectsLoading ? (
                <tr>
                  <td colSpan={4} className="px-6 py-8 text-center text-text-secondary">
                    Loading...
                  </td>
                </tr>
              ) : objects.length === 0 ? (
                <tr>
                  <td colSpan={4} className="px-6 py-8 text-center text-text-secondary">
                    {currentPath ? 'This folder is empty' : 'This bucket is empty'}
                  </td>
                </tr>
              ) : (
                objects.map((obj) => (
                  <tr key={obj.key} className="hover:bg-[#233648] transition-colors">
                    <td className="px-6 py-4">
                      {obj.is_dir ? (
                        <button
                          onClick={() => navigateToFolder(obj.key)}
                          className="flex items-center gap-2 text-white hover:text-primary transition-colors"
                        >
                          <Folder className="text-primary" size={18} />
                          <span>{obj.name}</span>
                        </button>
                      ) : (
                        <div className="flex items-center gap-2 text-white">
                          <File className="text-text-secondary" size={18} />
                          <span>{obj.name}</span>
                        </div>
                      )}
                    </td>
                    <td className="px-6 py-4 text-text-secondary">
                      {obj.is_dir ? '-' : formatBytes(obj.size, 1)}
                    </td>
                    <td className="px-6 py-4 text-text-secondary">
                      {formatDate(obj.last_modified)}
                    </td>
                    <td className="px-6 py-4 text-right">
                      {!obj.is_dir && (
                        <div className="flex items-center justify-end gap-2">
                          <button
                            onClick={() => {
                              const url = `${S3_ENDPOINT}/${selectedBucket}/${obj.key}`
                              copyToClipboard(url, 'Object URL')
                            }}
                            className="px-3 py-1.5 text-xs font-medium text-white bg-[#233648] hover:bg-[#2b4055] border border-border-dark rounded-lg transition-colors flex items-center gap-1.5"
                            title="Copy URL"
                          >
                            <LinkIcon size={14} />
                            Copy URL
                          </button>
                        </div>
                      )}
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  )
}

// Helper function for copy to clipboard (reuse from main component)
function copyToClipboard(text: string, label: string) {
  navigator.clipboard.writeText(text).then(() => {
    alert(`${label} copied to clipboard!`)
  }).catch(() => {
    alert(`Failed to copy. ${label}: ${text}`)
  })
}