import { useState } from 'react'
import { Plus, ArrowLeft, Key } from 'lucide-react'
import { toast } from 'sonner'
import { useEntries, useDeleteEntry } from '@/hooks/useVault'
import { EntryFormDialog, GrantAccessDialog, ConfirmDialog } from '@/components/dialogs'
import type { VaultEntry } from '@/services/api'
import { EntriesTable } from '@/components/vault/entries-table'

interface EntriesPageProps {
  vaultId: string
  isOwner?: boolean
  onNavigate: (to: 'vaults') => void
}

export function EntriesPage({ vaultId, isOwner, onNavigate }: EntriesPageProps) {
  const { data: entries = [], isLoading } = useEntries(vaultId)
  const deleteEntry = useDeleteEntry(vaultId)
  const [formOpen, setFormOpen] = useState(false)
  const [editEntry, setEditEntry] = useState<VaultEntry | undefined>()
  const [grantTarget, setGrantTarget] = useState<VaultEntry | null>(null)
  const [deleteTarget, setDeleteTarget] = useState<VaultEntry | null>(null)

  const handleDelete = async () => {
    if (!deleteTarget) return
    await deleteEntry.mutateAsync(deleteTarget.id)
    setDeleteTarget(null)
    toast.success('Entry deleted')
  }

  return (
    <div className='flex flex-col h-full bg-background'>
      <header className='flex items-center gap-4 p-6 border-b bg-card/50 backdrop-blur-sm sticky top-0 z-10'>
        <button 
          onClick={() => onNavigate('vaults')} 
          className='rounded-lg p-2 hover:bg-muted transition-colors'
          title='Back to Vaults'
        >
          <ArrowLeft className='h-5 w-5' />
        </button>
        <div className='flex-1 min-w-0'>
          <h1 className='text-2xl font-bold tracking-tight truncate'>
            Vault Credentials
          </h1>
          <p className='text-sm text-muted-foreground'>Securely store and manage your sensitive data.</p>
        </div>
        {isOwner && (
          <button 
            onClick={() => { setEditEntry(undefined); setFormOpen(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 Entry</span>
          </button>
        )}
      </header>

      <main className='flex-1 overflow-y-auto p-6'>
        {isLoading ? (
          <div className='space-y-4'>
            <div className='h-10 w-full rounded-lg bg-muted/20 animate-pulse' />
            {[1, 2, 3, 4, 5].map(i => (
              <div key={i} className='h-16 rounded-xl border bg-muted/10 animate-pulse' />
            ))}
          </div>
        ) : entries.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'>
              <Key className='h-8 w-8 text-muted-foreground' />
            </div>
            <h2 className='text-lg font-bold tracking-tight mb-1'>No entries found</h2>
            <p className='text-muted-foreground mb-6 text-sm leading-relaxed'>
              Add your first credential to this vault. You can store usernames, passwords, domains, and other sensitive details.
            </p>
           </div>
        ) : (
          <EntriesTable 
            entries={entries}
            isOwner={isOwner}
            onEdit={(entry) => { setEditEntry(entry); setFormOpen(true) }}
            onDelete={setDeleteTarget}
            onGrant={setGrantTarget}
          />
        )}
      </main>

      <EntryFormDialog
        open={formOpen}
        onOpenChange={(o) => { setFormOpen(o); if (!o) setEditEntry(undefined) }}
        vaultId={vaultId}
        editEntry={editEntry}
      />
      
      <GrantAccessDialog 
        open={!!grantTarget} 
        onOpenChange={(o) => { if (!o) setGrantTarget(null) }}
        scope='entry' 
        scopeId={grantTarget?.id || ''} 
        scopeLabel={grantTarget?.alias || grantTarget?.domain || grantTarget?.username || ''} 
      />

      <ConfirmDialog
        open={!!deleteTarget}
        onOpenChange={(o) => { if (!o) setDeleteTarget(null) }}
        title='Delete Entry'
        description={`Are you sure you want to delete "${deleteTarget?.alias || deleteTarget?.domain || deleteTarget?.username || 'this entry'}"? This action cannot be undone.`}
        onConfirm={handleDelete}
        loading={deleteEntry.isPending}
      />
    </div>
  )
}
