import { useState } from 'react'
import { Copy, Check } from 'lucide-react'
import { toast } from 'sonner'

export function PasswordCell({ vaultId, entryId, hasPassword }: { vaultId: string, entryId: string, hasPassword: boolean }) {
  const [copied, setCopied] = useState(false)
  const [loading, setLoading] = useState(false)

  const copy = async (e: React.MouseEvent) => {
    e.stopPropagation()
    setLoading(true)
    try {
      const { vaultApi } = await import('../../services/api')
      const { generateRSAKeyPair, exportPublicKeyPEM, decryptWithPrivateKey } = await import('../../lib/crypto')
      
      const keyPair = await generateRSAKeyPair()
      const publicKey = await exportPublicKeyPEM(keyPair.publicKey)
      const creds = await vaultApi.getEntryCredentials(vaultId, entryId, publicKey)
      
      let password = creds.password
      if (creds.encryptedPayload) {
        const payloadStr = await decryptWithPrivateKey(keyPair.privateKey, creds.encryptedPayload)
        const payload = JSON.parse(payloadStr)
        password = payload.password
      }

      if (password) {
        navigator.clipboard.writeText(password)
        setCopied(true); setTimeout(() => setCopied(false), 2000)
        toast.success('Password copied')
      } else {
        toast.error('No password stored')
      }
    } catch (err) {
      toast.error('Failed to retrieve password')
    } finally {
      setLoading(false)
    }
  }

  return (
    <span className='flex items-center gap-1'>
      {hasPassword ? 
      <>
        <span className='font-mono text-sm'>••••••••</span>
        <button onClick={copy} disabled={loading} className='ml-1 text-muted-foreground hover:text-foreground disabled:opacity-50'>
          {copied ? <Check className='h-3.5 w-3.5 text-green-500' /> : <Copy className='h-3.5 w-3.5' />}
        </button>
      </> : '—'}
    </span>
  )
}
 