import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { objectStorageApi, User, ServiceAccount, CreateUserRequest, CreateServiceAccountRequest } from '@/api/objectStorage'
import {
  Users,
  Key,
  UserPlus,
  KeyRound,
  Eye,
  EyeOff,
  AlertCircle,
  Trash2,
  Copy,
  RefreshCw,
  CheckCircle2
} from 'lucide-react'

interface UsersAndKeysProps {
  S3_ENDPOINT: string
}

export default function UsersAndKeys({ S3_ENDPOINT }: UsersAndKeysProps) {
  const [activeSubTab, setActiveSubTab] = useState<'users' | 'keys'>('users')
  const [showCreateUserModal, setShowCreateUserModal] = useState(false)
  const [newUserAccessKey, setNewUserAccessKey] = useState('')
  const [newUserSecretKey, setNewUserSecretKey] = useState('')
  const [showCreateKeyModal, setShowCreateKeyModal] = useState(false)
  const [newKeyParentUser, setNewKeyParentUser] = useState('')
  const [newKeyPolicy, setNewKeyPolicy] = useState('')
  const [newKeyExpiration, setNewKeyExpiration] = useState('')
  const [createdKey, setCreatedKey] = useState<ServiceAccount | null>(null)
  const [showSecretKey, setShowSecretKey] = useState(false)
  const [deleteConfirmUser, setDeleteConfirmUser] = useState<string | null>(null)
  const [deleteConfirmKey, setDeleteConfirmKey] = useState<string | null>(null)
  const [isRefreshingUsers, setIsRefreshingUsers] = useState(false)
  const [isRefreshingKeys, setIsRefreshingKeys] = useState(false)
  const queryClient = useQueryClient()

  // Fetch users
  const { data: users = [], isLoading: usersLoading } = useQuery<User[]>({
    queryKey: ['object-storage-users'],
    queryFn: objectStorageApi.listUsers,
    refetchInterval: 10000, // Auto-refresh every 10 seconds
  })

  // Fetch service accounts (keys)
  const { data: serviceAccounts = [], isLoading: keysLoading } = useQuery<ServiceAccount[]>({
    queryKey: ['object-storage-service-accounts'],
    queryFn: objectStorageApi.listServiceAccounts,
    refetchInterval: 10000, // Auto-refresh every 10 seconds
  })

  // Create user mutation with optimistic update
  const createUserMutation = useMutation({
    mutationFn: (data: CreateUserRequest) => objectStorageApi.createUser(data),
    onMutate: async (data: CreateUserRequest) => {
      // Cancel any outgoing refetches
      await queryClient.cancelQueries({ queryKey: ['object-storage-users'] })
      
      // Snapshot the previous value
      const previousUsers = queryClient.getQueryData(['object-storage-users'])
      
      // Optimistically add the new user to the list
      queryClient.setQueryData(['object-storage-users'], (old: User[] = []) => {
        const newUser: User = {
          access_key: data.access_key,
          status: 'enabled',
          created_at: new Date().toISOString(),
        }
        return [...old, newUser]
      })
      
      // Close modal immediately
      setShowCreateUserModal(false)
      setNewUserAccessKey('')
      setNewUserSecretKey('')
      
      // Return a context object with the snapshotted value
      return { previousUsers }
    },
    onError: (error: any, _data: CreateUserRequest, context: any) => {
      // If the mutation fails, use the context returned from onMutate to roll back
      if (context?.previousUsers) {
        queryClient.setQueryData(['object-storage-users'], context.previousUsers)
      }
      // Reopen modal on error
      setShowCreateUserModal(true)
      alert(error.response?.data?.error || 'Failed to create user')
    },
    onSuccess: () => {
      // Refetch to ensure we have the latest data from server
      queryClient.invalidateQueries({ queryKey: ['object-storage-users'] })
      alert('User created successfully!')
    },
    onSettled: () => {
      // Always refetch after error or success to ensure consistency
      queryClient.invalidateQueries({ queryKey: ['object-storage-users'] })
    },
  })

  // Delete user mutation
  const deleteUserMutation = useMutation({
    mutationFn: (accessKey: string) => objectStorageApi.deleteUser(accessKey),
    onMutate: async (accessKey: string) => {
      await queryClient.cancelQueries({ queryKey: ['object-storage-users'] })
      const previousUsers = queryClient.getQueryData(['object-storage-users'])
      queryClient.setQueryData(['object-storage-users'], (old: User[] = []) =>
        old.filter((user) => user.access_key !== accessKey)
      )
      return { previousUsers }
    },
    onError: (error: any, _accessKey: string, context: any) => {
      if (context?.previousUsers) {
        queryClient.setQueryData(['object-storage-users'], context.previousUsers)
      }
      alert(error.response?.data?.error || 'Failed to delete user')
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['object-storage-users'] })
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['object-storage-users'] })
    },
  })

  // Create service account mutation with optimistic update
  const createServiceAccountMutation = useMutation({
    mutationFn: (data: CreateServiceAccountRequest) => objectStorageApi.createServiceAccount(data),
    onMutate: async (_data: CreateServiceAccountRequest) => {
      // Cancel any outgoing refetches
      await queryClient.cancelQueries({ queryKey: ['object-storage-service-accounts'] })
      
      // Snapshot the previous value
      const previousAccounts = queryClient.getQueryData(['object-storage-service-accounts'])
      
      // Close modal immediately (we'll show created key modal after success)
      setShowCreateKeyModal(false)
      setNewKeyParentUser('')
      setNewKeyPolicy('')
      setNewKeyExpiration('')
      
      // Return a context object with the snapshotted value
      return { previousAccounts }
    },
    onError: (error: any, _data: CreateServiceAccountRequest, context: any) => {
      // If the mutation fails, use the context returned from onMutate to roll back
      if (context?.previousAccounts) {
        queryClient.setQueryData(['object-storage-service-accounts'], context.previousAccounts)
      }
      // Reopen modal on error
      setShowCreateKeyModal(true)
      alert(error.response?.data?.error || 'Failed to create access key')
    },
    onSuccess: (data: ServiceAccount) => {
      // Optimistically add the new service account to the list
      queryClient.setQueryData(['object-storage-service-accounts'], (old: ServiceAccount[] = []) => {
        return [...old, data]
      })
      
      // Show created key modal with secret key
      setCreatedKey(data)
      
      // Refetch to ensure we have the latest data from server
      queryClient.invalidateQueries({ queryKey: ['object-storage-service-accounts'] })
    },
    onSettled: () => {
      // Always refetch after error or success to ensure consistency
      queryClient.invalidateQueries({ queryKey: ['object-storage-service-accounts'] })
    },
  })

  // Delete service account mutation
  const deleteServiceAccountMutation = useMutation({
    mutationFn: (accessKey: string) => objectStorageApi.deleteServiceAccount(accessKey),
    onMutate: async (accessKey: string) => {
      await queryClient.cancelQueries({ queryKey: ['object-storage-service-accounts'] })
      const previousAccounts = queryClient.getQueryData(['object-storage-service-accounts'])
      queryClient.setQueryData(['object-storage-service-accounts'], (old: ServiceAccount[] = []) =>
        old.filter((account) => account.access_key !== accessKey)
      )
      return { previousAccounts }
    },
    onError: (error: any, _accessKey: string, context: any) => {
      if (context?.previousAccounts) {
        queryClient.setQueryData(['object-storage-service-accounts'], context.previousAccounts)
      }
      alert(error.response?.data?.error || 'Failed to delete access key')
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['object-storage-service-accounts'] })
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['object-storage-service-accounts'] })
    },
  })

  // Refresh users
  const handleRefreshUsers = async () => {
    setIsRefreshingUsers(true)
    try {
      await queryClient.invalidateQueries({ queryKey: ['object-storage-users'] })
      await queryClient.refetchQueries({ queryKey: ['object-storage-users'] })
      setTimeout(() => {
        alert('Users refreshed successfully!')
      }, 300)
    } catch (error) {
      alert('Failed to refresh users')
    } finally {
      setIsRefreshingUsers(false)
    }
  }

  // Refresh keys
  const handleRefreshKeys = async () => {
    setIsRefreshingKeys(true)
    try {
      await queryClient.invalidateQueries({ queryKey: ['object-storage-service-accounts'] })
      await queryClient.refetchQueries({ queryKey: ['object-storage-service-accounts'] })
      setTimeout(() => {
        alert('Access keys refreshed successfully!')
      }, 300)
    } catch (error) {
      alert('Failed to refresh access keys')
    } finally {
      setIsRefreshingKeys(false)
    }
  }

  // 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
  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:', error)
      // Fallback
      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="space-y-6">
      {/* Sub-tabs for Users and Keys */}
      <div className="flex items-center gap-2 border-b border-border-dark">
        <button
          onClick={() => setActiveSubTab('users')}
          className={`px-4 py-2 text-sm font-medium transition-colors ${
            activeSubTab === 'users'
              ? 'text-primary border-b-2 border-primary'
              : 'text-text-secondary hover:text-white'
          }`}
        >
          <div className="flex items-center gap-2">
            <Users size={18} />
            <span>Users ({users.length})</span>
          </div>
        </button>
        <button
          onClick={() => setActiveSubTab('keys')}
          className={`px-4 py-2 text-sm font-medium transition-colors ${
            activeSubTab === 'keys'
              ? 'text-primary border-b-2 border-primary'
              : 'text-text-secondary hover:text-white'
          }`}
        >
          <div className="flex items-center gap-2">
            <Key size={18} />
            <span>Access Keys ({serviceAccounts.length})</span>
          </div>
        </button>
      </div>

      {/* Users Tab */}
      {activeSubTab === 'users' && (
        <div className="space-y-4">
          {/* Header with actions */}
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-white text-xl font-bold">IAM Users</h2>
              <p className="text-text-secondary text-sm mt-1">
                Manage MinIO IAM users for accessing object storage
              </p>
            </div>
            <div className="flex gap-2">
              <button
                onClick={handleRefreshUsers}
                disabled={isRefreshingUsers}
                className="px-4 py-2 bg-[#233648] hover:bg-[#2b4055] text-white text-sm font-medium rounded-lg border border-border-dark transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                <RefreshCw size={16} className={isRefreshingUsers ? 'animate-spin' : ''} />
                {isRefreshingUsers ? 'Refreshing...' : 'Refresh'}
              </button>
              <button
                onClick={() => setShowCreateUserModal(true)}
                className="px-4 py-2 bg-primary hover:bg-blue-600 text-white text-sm font-medium rounded-lg transition-colors flex items-center gap-2"
              >
                <UserPlus size={16} />
                Create User
              </button>
            </div>
          </div>

          {/* Users Table */}
          {usersLoading ? (
            <div className="bg-[#1c2936] border border-border-dark rounded-lg p-8 text-center">
              <p className="text-text-secondary text-sm">Loading users...</p>
            </div>
          ) : users.length === 0 ? (
            <div className="bg-[#1c2936] border border-border-dark rounded-lg p-8 text-center">
              <Users className="mx-auto mb-4 text-text-secondary" size={48} />
              <p className="text-text-secondary text-sm mb-4">No users found</p>
              <button
                onClick={() => setShowCreateUserModal(true)}
                className="px-4 py-2 bg-primary hover:bg-blue-600 text-white text-sm font-medium rounded-lg transition-colors"
              >
                Create First User
              </button>
            </div>
          ) : (
            <div className="bg-[#1c2936] border border-border-dark rounded-lg overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-[#16202a] border-b border-border-dark">
                    <tr>
                      <th className="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
                        Access Key
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
                        Status
                      </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">
                    {users.map((user) => (
                      <tr key={user.access_key} className="hover:bg-[#233648] transition-colors">
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="flex items-center gap-2">
                            <Users size={16} className="text-primary" />
                            <span className="text-white font-mono text-sm">{user.access_key}</span>
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <span
                            className={`inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium ${
                              user.status === 'enabled'
                                ? 'bg-green-500/10 text-green-500 border border-green-500/20'
                                : 'bg-red-500/10 text-red-500 border border-red-500/20'
                            }`}
                          >
                            {user.status === 'enabled' ? (
                              <>
                                <CheckCircle2 size={12} className="mr-1" />
                                Enabled
                              </>
                            ) : (
                              'Disabled'
                            )}
                          </span>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-text-secondary text-sm">
                          {formatDate(user.created_at)}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="flex items-center justify-end gap-2">
                            <button
                              onClick={async () => {
                                await copyToClipboard(user.access_key, 'Access Key')
                              }}
                              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 Access Key"
                            >
                              <Copy size={14} />
                              Copy
                            </button>
                            <button
                              onClick={() => setDeleteConfirmUser(user.access_key)}
                              disabled={deleteUserMutation.isPending}
                              className="px-3 py-1.5 text-xs font-medium text-red-400 bg-red-500/10 hover:bg-red-500/20 border border-red-500/20 rounded-lg transition-colors flex items-center gap-1.5 disabled:opacity-50 disabled:cursor-not-allowed"
                              title="Delete User"
                            >
                              <Trash2 size={14} />
                              Delete
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Keys Tab */}
      {activeSubTab === 'keys' && (
        <div className="space-y-4">
          {/* Header with actions */}
          <div className="flex items-center justify-between">
            <div>
              <h2 className="text-white text-xl font-bold">Access Keys</h2>
              <p className="text-text-secondary text-sm mt-1">
                Manage service account access keys for programmatic access
              </p>
            </div>
            <div className="flex gap-2">
              <button
                onClick={handleRefreshKeys}
                disabled={isRefreshingKeys}
                className="px-4 py-2 bg-[#233648] hover:bg-[#2b4055] text-white text-sm font-medium rounded-lg border border-border-dark transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                <RefreshCw size={16} className={isRefreshingKeys ? 'animate-spin' : ''} />
                {isRefreshingKeys ? 'Refreshing...' : 'Refresh'}
              </button>
              <button
                onClick={() => {
                  if (users.length === 0) {
                    alert('Please create at least one user before creating access keys')
                    setActiveSubTab('users')
                    return
                  }
                  setShowCreateKeyModal(true)
                }}
                className="px-4 py-2 bg-primary hover:bg-blue-600 text-white text-sm font-medium rounded-lg transition-colors flex items-center gap-2"
              >
                <KeyRound size={16} />
                Create Access Key
              </button>
            </div>
          </div>

          {/* Keys Table */}
          {keysLoading ? (
            <div className="bg-[#1c2936] border border-border-dark rounded-lg p-8 text-center">
              <p className="text-text-secondary text-sm">Loading access keys...</p>
            </div>
          ) : serviceAccounts.length === 0 ? (
            <div className="bg-[#1c2936] border border-border-dark rounded-lg p-8 text-center">
              <Key className="mx-auto mb-4 text-text-secondary" size={48} />
              <p className="text-text-secondary text-sm mb-4">No access keys found</p>
              <button
                onClick={() => {
                  if (users.length === 0) {
                    alert('Please create at least one user before creating access keys')
                    setActiveSubTab('users')
                    return
                  }
                  setShowCreateKeyModal(true)
                }}
                className="px-4 py-2 bg-primary hover:bg-blue-600 text-white text-sm font-medium rounded-lg transition-colors"
              >
                Create First Access Key
              </button>
            </div>
          ) : (
            <div className="bg-[#1c2936] border border-border-dark rounded-lg overflow-hidden">
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-[#16202a] border-b border-border-dark">
                    <tr>
                      <th className="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
                        Access Key
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
                        Parent User
                      </th>
                      <th className="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
                        Expiration
                      </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">
                    {serviceAccounts.map((account) => (
                      <tr key={account.access_key} className="hover:bg-[#233648] transition-colors">
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="flex items-center gap-2">
                            <Key size={16} className="text-primary" />
                            <span className="text-white font-mono text-sm">{account.access_key}</span>
                          </div>
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-text-secondary text-sm">
                          {account.parent_user}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-text-secondary text-sm">
                          {account.expiration ? formatDate(account.expiration) : 'Never'}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap text-text-secondary text-sm">
                          {formatDate(account.created_at)}
                        </td>
                        <td className="px-6 py-4 whitespace-nowrap">
                          <div className="flex items-center justify-end gap-2">
                            <button
                              onClick={async () => {
                                await copyToClipboard(account.access_key, 'Access Key')
                              }}
                              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 Access Key"
                            >
                              <Copy size={14} />
                              Copy
                            </button>
                            <button
                              onClick={() => setDeleteConfirmKey(account.access_key)}
                              disabled={deleteServiceAccountMutation.isPending}
                              className="px-3 py-1.5 text-xs font-medium text-red-400 bg-red-500/10 hover:bg-red-500/20 border border-red-500/20 rounded-lg transition-colors flex items-center gap-1.5 disabled:opacity-50 disabled:cursor-not-allowed"
                              title="Delete Access Key"
                            >
                              <Trash2 size={14} />
                              Delete
                            </button>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Create User Modal */}
      {showCreateUserModal && (
        <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 IAM User</h2>
              <button
                onClick={() => {
                  setShowCreateUserModal(false)
                  setNewUserAccessKey('')
                  setNewUserSecretKey('')
                }}
                className="text-text-secondary hover:text-white transition-colors"
              >
                ✕
              </button>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-white text-sm font-medium mb-2">Access Key</label>
                <input
                  type="text"
                  value={newUserAccessKey}
                  onChange={(e) => setNewUserAccessKey(e.target.value)}
                  placeholder="e.g., myuser"
                  className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2 text-white text-sm focus:ring-1 focus:ring-primary focus:border-primary outline-none font-mono"
                  autoFocus
                />
                <p className="text-text-secondary text-xs mt-2">
                  Access key must be unique and follow MinIO naming conventions
                </p>
              </div>

              <div>
                <label className="block text-white text-sm font-medium mb-2">Secret Key</label>
                <div className="relative">
                  <input
                    type={showSecretKey ? 'text' : 'password'}
                    value={newUserSecretKey}
                    onChange={(e) => setNewUserSecretKey(e.target.value)}
                    placeholder="Enter secret key"
                    className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2 pr-10 text-white text-sm focus:ring-1 focus:ring-primary focus:border-primary outline-none font-mono"
                  />
                  <button
                    type="button"
                    onClick={() => setShowSecretKey(!showSecretKey)}
                    className="absolute right-3 top-1/2 -translate-y-1/2 text-text-secondary hover:text-white"
                  >
                    {showSecretKey ? <EyeOff size={18} /> : <Eye size={18} />}
                  </button>
                </div>
                <p className="text-text-secondary text-xs mt-2">
                  Secret key must be at least 8 characters long
                </p>
              </div>

              <div className="flex gap-3 justify-end pt-4">
                <button
                  onClick={() => {
                    setShowCreateUserModal(false)
                    setNewUserAccessKey('')
                    setNewUserSecretKey('')
                  }}
                  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 (!newUserAccessKey.trim()) {
                      alert('Please enter an access key')
                      return
                    }
                    if (!newUserSecretKey.trim() || newUserSecretKey.length < 8) {
                      alert('Please enter a secret key (minimum 8 characters)')
                      return
                    }
                    createUserMutation.mutate({
                      access_key: newUserAccessKey.trim(),
                      secret_key: newUserSecretKey,
                    })
                  }}
                  disabled={createUserMutation.isPending || !newUserAccessKey.trim() || !newUserSecretKey.trim()}
                  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"
                >
                  {createUserMutation.isPending ? 'Creating...' : 'Create User'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Create Access Key Modal */}
      {showCreateKeyModal && (
        <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 Access Key</h2>
              <button
                onClick={() => {
                  setShowCreateKeyModal(false)
                  setNewKeyParentUser('')
                  setNewKeyPolicy('')
                  setNewKeyExpiration('')
                }}
                className="text-text-secondary hover:text-white transition-colors"
              >
                ✕
              </button>
            </div>

            <div className="space-y-4">
              <div>
                <label className="block text-white text-sm font-medium mb-2">Parent User</label>
                <select
                  value={newKeyParentUser}
                  onChange={(e) => setNewKeyParentUser(e.target.value)}
                  className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2 text-white text-sm focus:ring-1 focus:ring-primary focus:border-primary outline-none"
                  autoFocus
                >
                  <option value="">-- Select User --</option>
                  {users.map((user) => (
                    <option key={user.access_key} value={user.access_key}>
                      {user.access_key}
                    </option>
                  ))}
                </select>
                <p className="text-text-secondary text-xs mt-2">
                  Select the IAM user this access key will belong to
                </p>
              </div>

              <div>
                <label className="block text-white text-sm font-medium mb-2">
                  Policy (Optional)
                </label>
                <textarea
                  value={newKeyPolicy}
                  onChange={(e) => setNewKeyPolicy(e.target.value)}
                  placeholder='{"Version":"2012-10-17","Statement":[...]}'
                  rows={4}
                  className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2 text-white text-sm focus:ring-1 focus:ring-primary focus:border-primary outline-none font-mono"
                />
                <p className="text-text-secondary text-xs mt-2">
                  JSON policy document (leave empty for default permissions)
                </p>
              </div>

              <div>
                <label className="block text-white text-sm font-medium mb-2">
                  Expiration (Optional)
                </label>
                <input
                  type="datetime-local"
                  value={newKeyExpiration}
                  onChange={(e) => setNewKeyExpiration(e.target.value)}
                  className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2 text-white text-sm focus:ring-1 focus:ring-primary focus:border-primary outline-none"
                />
                <p className="text-text-secondary text-xs mt-2">
                  Leave empty for no expiration
                </p>
              </div>

              <div className="flex gap-3 justify-end pt-4">
                <button
                  onClick={() => {
                    setShowCreateKeyModal(false)
                    setNewKeyParentUser('')
                    setNewKeyPolicy('')
                    setNewKeyExpiration('')
                  }}
                  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 (!newKeyParentUser.trim()) {
                      alert('Please select a parent user')
                      return
                    }
                    createServiceAccountMutation.mutate({
                      parent_user: newKeyParentUser.trim(),
                      policy: newKeyPolicy.trim() || undefined,
                      expiration: newKeyExpiration ? new Date(newKeyExpiration).toISOString() : undefined,
                    })
                  }}
                  disabled={createServiceAccountMutation.isPending || !newKeyParentUser.trim()}
                  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"
                >
                  {createServiceAccountMutation.isPending ? 'Creating...' : 'Create Access Key'}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Delete User Confirmation Dialog */}
      {deleteConfirmUser && (
        <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 gap-3 mb-4">
              <div className="p-2 bg-red-500/10 rounded-lg">
                <AlertCircle className="text-red-400" size={24} />
              </div>
              <div>
                <h2 className="text-white text-lg font-bold">Delete User</h2>
                <p className="text-text-secondary text-sm">This action cannot be undone</p>
              </div>
            </div>
            <div className="mb-6">
              <p className="text-white text-sm mb-2">
                Are you sure you want to delete user <span className="font-mono font-semibold text-primary">{deleteConfirmUser}</span>?
              </p>
              <p className="text-text-secondary text-xs">
                All access keys associated with this user will also be deleted. This action cannot be undone.
              </p>
            </div>
            <div className="flex gap-3 justify-end">
              <button
                onClick={() => setDeleteConfirmUser(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={() => {
                  deleteUserMutation.mutate(deleteConfirmUser)
                  setDeleteConfirmUser(null)
                }}
                disabled={deleteUserMutation.isPending}
                className="px-4 py-2 bg-red-500 hover:bg-red-600 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                <Trash2 size={16} />
                {deleteUserMutation.isPending ? 'Deleting...' : 'Delete User'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Delete Key Confirmation Dialog */}
      {deleteConfirmKey && (
        <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 gap-3 mb-4">
              <div className="p-2 bg-red-500/10 rounded-lg">
                <AlertCircle className="text-red-400" size={24} />
              </div>
              <div>
                <h2 className="text-white text-lg font-bold">Delete Access Key</h2>
                <p className="text-text-secondary text-sm">This action cannot be undone</p>
              </div>
            </div>
            <div className="mb-6">
              <p className="text-white text-sm mb-2">
                Are you sure you want to delete access key <span className="font-mono font-semibold text-primary">{deleteConfirmKey}</span>?
              </p>
              <p className="text-text-secondary text-xs">
                Applications using this access key will lose access immediately. This action cannot be undone.
              </p>
            </div>
            <div className="flex gap-3 justify-end">
              <button
                onClick={() => setDeleteConfirmKey(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={() => {
                  deleteServiceAccountMutation.mutate(deleteConfirmKey)
                  setDeleteConfirmKey(null)
                }}
                disabled={deleteServiceAccountMutation.isPending}
                className="px-4 py-2 bg-red-500 hover:bg-red-600 text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2"
              >
                <Trash2 size={16} />
                {deleteServiceAccountMutation.isPending ? 'Deleting...' : 'Delete Key'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Created Key Modal (shows secret key once) */}
      {createdKey && (
        <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-lg w-full mx-4">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-white text-xl font-bold">Access Key Created</h2>
              <button
                onClick={() => {
                  setCreatedKey(null)
                  setShowSecretKey(false)
                }}
                className="text-text-secondary hover:text-white transition-colors"
              >
                ✕
              </button>
            </div>

            <div className="space-y-4">
              <div className="bg-orange-500/10 border border-orange-500/20 rounded-lg p-4">
                <div className="flex items-start gap-2">
                  <AlertCircle className="text-orange-400 mt-0.5" size={20} />
                  <div>
                    <p className="text-orange-400 text-sm font-medium mb-1">Important</p>
                    <p className="text-orange-300 text-xs">
                      Save these credentials now. The secret key will not be shown again.
                    </p>
                  </div>
                </div>
              </div>

              <div>
                <label className="block text-white text-sm font-medium mb-2">Access Key</label>
                <div className="flex items-center gap-2">
                  <input
                    type="text"
                    value={createdKey.access_key}
                    readOnly
                    className="flex-1 bg-[#233648] border border-border-dark rounded-lg px-4 py-2 text-white text-sm font-mono"
                  />
                  <button
                    onClick={() => copyToClipboard(createdKey.access_key, 'Access Key')}
                    className="px-3 py-2 bg-[#233648] hover:bg-[#2b4055] border border-border-dark rounded-lg text-white text-sm transition-colors"
                  >
                    <Copy size={16} />
                  </button>
                </div>
              </div>

              <div>
                <label className="block text-white text-sm font-medium mb-2">Secret Key</label>
                <div className="flex items-center gap-2">
                  <div className="relative flex-1">
                    <input
                      type={showSecretKey ? 'text' : 'password'}
                      value={createdKey.secret_key || ''}
                      readOnly
                      className="w-full bg-[#233648] border border-border-dark rounded-lg px-4 py-2 pr-10 text-white text-sm font-mono"
                    />
                    <button
                      type="button"
                      onClick={() => setShowSecretKey(!showSecretKey)}
                      className="absolute right-3 top-1/2 -translate-y-1/2 text-text-secondary hover:text-white"
                    >
                      {showSecretKey ? <EyeOff size={18} /> : <Eye size={18} />}
                    </button>
                  </div>
                  <button
                    onClick={() => copyToClipboard(createdKey.secret_key || '', 'Secret Key')}
                    className="px-3 py-2 bg-[#233648] hover:bg-[#2b4055] border border-border-dark rounded-lg text-white text-sm transition-colors"
                  >
                    <Copy size={16} />
                  </button>
                </div>
              </div>

              <div>
                <label className="block text-white text-sm font-medium mb-2">Endpoint</label>
                <div className="flex items-center gap-2">
                  <input
                    type="text"
                    value={S3_ENDPOINT}
                    readOnly
                    className="flex-1 bg-[#233648] border border-border-dark rounded-lg px-4 py-2 text-white text-sm font-mono"
                  />
                  <button
                    onClick={() => copyToClipboard(S3_ENDPOINT, 'Endpoint')}
                    className="px-3 py-2 bg-[#233648] hover:bg-[#2b4055] border border-border-dark rounded-lg text-white text-sm transition-colors"
                  >
                    <Copy size={16} />
                  </button>
                </div>
              </div>

              <div className="flex gap-3 justify-end pt-4">
                <button
                  onClick={() => {
                    setCreatedKey(null)
                    setShowSecretKey(false)
                  }}
                  className="px-4 py-2 bg-primary hover:bg-blue-600 text-white text-sm font-medium rounded-lg transition-colors"
                >
                  I've Saved These Credentials
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
