import { useState } from 'react'
import { MdAdd, MdVpnKey, MdDelete } from 'react-icons/md'
import { createVault, deleteVault } from '../api.js'
import './VaultList.css'

export default function VaultList({ userId, vaults, selectedVaultId, onSelect, onRefresh, addToast }) {
  const [newVaultName, setNewVaultName] = useState('')
  const [creating, setCreating] = useState(false)
  const [showInput, setShowInput] = useState(false)

  async function handleCreate(e) {
    e.preventDefault()
    if (!newVaultName.trim()) return
    setCreating(true)
    try {
      await createVault(userId, newVaultName.trim())
      setNewVaultName('')
      setShowInput(false)
      addToast('Vault created', 'success')
      onRefresh()
    } catch (err) {
      addToast(err.message || 'Failed to create vault', 'error')
    } finally {
      setCreating(false)
    }
  }

  async function handleDelete(e, vaultId) {
    e.stopPropagation()
    if (!window.confirm('Delete this vault and all its passwords?')) return
    try {
      await deleteVault(userId, vaultId)
      addToast('Vault deleted', 'success')
      onRefresh()
    } catch (err) {
      addToast(err.message || 'Failed to delete vault', 'error')
    }
  }

  return (
    <div className="vault-list">
      <div className="vault-list-header">
        <h2>
          <MdVpnKey className="vault-list-icon" />
          Vaults
        </h2>
        <button
          className="btn-icon"
          title="New vault"
          onClick={() => setShowInput(v => !v)}
        >
          <MdAdd size={20} />
        </button>
      </div>

      {showInput && (
        <form onSubmit={handleCreate} className="vault-create-form">
          <input
            type="text"
            value={newVaultName}
            onChange={e => setNewVaultName(e.target.value)}
            placeholder="Vault name"
            autoFocus
            maxLength={100}
          />
          <button
            type="submit"
            className="btn btn-primary"
            disabled={creating || !newVaultName.trim()}
          >
            {creating ? '…' : 'Add'}
          </button>
        </form>
      )}

      <ul className="vault-items">
        {vaults.length === 0 && (
          <li className="vault-empty">No vaults yet</li>
        )}
        {vaults.map(vault => (
          <li
            key={vault.id}
            className={`vault-item ${selectedVaultId === vault.id ? 'vault-item--active' : ''}`}
            onClick={() => onSelect(vault)}
          >
            <span className="vault-item-name">{vault.name}</span>
            <button
              className="btn-icon vault-delete-btn"
              title="Delete vault"
              onClick={e => handleDelete(e, vault.id)}
            >
              <MdDelete size={16} />
            </button>
          </li>
        ))}
      </ul>
    </div>
  )
}
