import { useState } from 'react'
import { FolderLock, MoreHorizontal, Plus, Shield, Trash2, Pencil, ScrollText, ChevronRight } from 'lucide-react'
import { useVaults, useDeleteVault, useMe } from '@/hooks/useVault'
import { VaultCreateDialog, GrantAccessDialog, ConfirmDialog } from '@/components/dialogs'
import type { Vault } from '@/services/api'

interface VaultPageProps {
  onNavigate: (to: 'entries' | 'audit', vaultId?: string) => void
}

export function VaultPage({ onNavigate }: VaultPageProps) {
  const { data: me } = useMe()
  const { data: vaults = [], isLoading } = useVaults()
  const deleteVault = useDeleteVault()
  const [createOpen, setCreateOpen] = useState(false)
  const [editTarget, setEditTarget] = useState<Vault | null>(null)
  const [deleteTarget, setDeleteTarget] = useState<Vault | null>(null)
  const [grantTarget, setGrantTarget] = useState<Vault | null>(null)
  const [menuOpen, setMenuOpen] = useState<string | null>(null)

  const handleDelete = async () => {
    if (!deleteTarget) return
    await deleteVault.mutateAsync(deleteTarget.id)
    setDeleteTarget(null)
  }

  const isAdmin = me?.role === 'admin'

  return (
    <div className='flex flex-col h-full bg-background'>
      {/* Header */}
      <header className='flex items-center justify-between px-6 py-4 border-b border-border'>
        <div className='flex items-center gap-3'>
          <div className='rounded-xl bg-primary/10 p-2.5'>
            <Shield className='h-6 w-6 text-primary' />
          </div>
          <div>
            <h1 className='text-2xl font-bold tracking-tight text-foreground'>Vaults</h1>
            <p className='text-sm text-muted-foreground'>Securely manage and share your encrypted credentials.</p>
          </div>
        </div>
        <div className='flex items-center gap-2'>
          {isAdmin && (
            <button
              onClick={() => onNavigate('audit')}
              className='inline-flex items-center gap-2 rounded-lg border border-input bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm hover:bg-muted transition-all'
            >
              <ScrollText className='h-4 w-4' />
              <span>Audit Log</span>
            </button>
          )}
          <button
            onClick={() => { setEditTarget(null); setCreateOpen(true) }}
            className='inline-flex items-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground shadow-sm hover:bg-primary/90 transition-all hover:scale-[1.02] active:scale-[0.98]'
          >
            <Plus className='h-4 w-4' /> 
            <span>New Vault</span>
          </button>
        </div>
      </header>

      {/* Content */}
      <main className='flex-1 overflow-y-auto p-6'>
        {isLoading ? (
          <div className='grid gap-4 sm:grid-cols-2 lg:grid-cols-3'>
            {[1, 2, 3].map((i) => (
              <div key={i} className='h-40 rounded-xl border bg-muted/20 animate-pulse' />
            ))}
          </div>
        ) : vaults.length === 0 ? (
          <div className='flex flex-col items-center justify-center p-6 py-12 text-center max-w-sm mx-auto mt-8'>
            <div className='mb-4 rounded-full bg-muted p-4 border border-primary/10'>
              <FolderLock className='h-8 w-8 text-muted-foreground' />
            </div>
            <h2 className='text-lg font-bold tracking-tight mb-1'>No vaults found</h2>
            <p className='text-muted-foreground mb-6 text-sm leading-relaxed'>
              Create your first vault to start storing encrypted credentials for your projects and teams.
            </p>
          </div>
        ) : (
          <div className='grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4'>
            {vaults.map((vault) => (
              <div
                key={vault.id}
                className='group relative rounded-xl border bg-card p-4 cursor-pointer hover:shadow-md hover:border-primary/50 transition-all'
                onClick={() => onNavigate('entries', vault.id)}
              >
                <div className='flex items-start justify-between mb-4'>
                  <div className='rounded-lg bg-primary/10 p-2.5 transition-colors group-hover:bg-primary/20'>
                    <FolderLock className='h-5 w-5 text-primary' />
                  </div>
                  {vault.is_owner && (
                    <div className='relative'> 
                      <button
                        onClick={(e) => { e.stopPropagation(); setMenuOpen(menuOpen === vault.id ? null : vault.id) }}
                        className='h-8 w-8 flex items-center justify-center rounded-md hover:bg-muted opacity-0 group-hover:opacity-100 transition-opacity'
                      >
                        <MoreHorizontal className='h-4 w-4' />
                      </button>
                      {menuOpen === vault.id && (
                        <>
                          <div className='fixed inset-0 z-10' onClick={(e) => { e.stopPropagation(); setMenuOpen(null) }} />
                          <div className='absolute right-0 top-9 z-20 w-40 rounded-lg border bg-popover shadow-lg py-1.5 overflow-hidden animate-in fade-in zoom-in-95 duration-100'>
                            <button
                              onClick={(e) => { 
                                e.stopPropagation(); 
                                setMenuOpen(null); 
                                setEditTarget(vault);
                                setCreateOpen(true);
                              }}
                              className='w-full flex items-center gap-2 px-3 py-2 text-sm hover:bg-muted text-left transition-colors'
                            >
                              <Pencil className='h-4 w-4 text-muted-foreground' /> 
                              <span>Edit</span>
                            </button>
                            <button
                              onClick={(e) => { e.stopPropagation(); setMenuOpen(null); setGrantTarget(vault) }}
                              className='w-full flex items-center gap-2 px-3 py-2 text-sm hover:bg-muted text-left transition-colors'
                            >
                              <Shield className='h-4 w-4 text-muted-foreground' /> 
                              <span>Access</span>
                            </button>
                            <div className='h-px bg-border my-1' />
                            <button
                              onClick={(e) => { e.stopPropagation(); setMenuOpen(null); setDeleteTarget(vault) }}
                              className='w-full flex items-center gap-2 px-3 py-2 text-sm hover:bg-muted text-left text-destructive transition-colors'
                            >
                              <Trash2 className='h-4 w-4' /> 
                              <span>Delete</span>
                            </button>
                          </div>
                        </>
                      )}
                    </div>
                  )}
                </div>

                <div className='space-y-1'>
                  <p className='font-bold text-lg text-foreground truncate'>{vault.name}</p>
                  <p className='text-xs text-muted-foreground font-medium'>
                    {vault.is_owner ? 'Owner' : 'Shared with you'}
                  </p>
                </div>

                <div className='flex items-center justify-between mt-6 pt-4 border-t'>
                  <span className='text-[10px] tracking-wider  text-muted-foreground'>
                    Created {new Date(vault.created_at).toLocaleDateString()}
                  </span>
                  <div className='rounded-full p-1 group-hover:bg-primary/10 transition-colors'>
                    <ChevronRight className='h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors' />
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </main>

      <VaultCreateDialog 
        open={createOpen} 
        onOpenChange={setCreateOpen} 
        editVault={editTarget || undefined}
      />

      <GrantAccessDialog
        open={!!grantTarget}
        onOpenChange={(o) => { if (!o) setGrantTarget(null) }}
        scope='vault'
        scopeId={grantTarget?.id || ''}
        scopeLabel={grantTarget?.name || ''}
      />

      <ConfirmDialog
        open={!!deleteTarget}
        onOpenChange={(o) => { if (!o) setDeleteTarget(null) }}
        title='Delete Vault'
        description={`Are you sure you want to delete "${deleteTarget?.name}"? This will permanently delete all credentials within this vault.`}
        onConfirm={handleDelete}
        loading={deleteVault.isPending}
      />
    </div>
  )
}

