import { useState, useEffect } from 'react'
import {
  MdAdd,
  MdContentCopy,
  MdVisibility,
  MdVisibilityOff,
  MdEdit,
  MdDelete,
  MdLink,
  MdPerson,
  MdLabel,
} from 'react-icons/md'
import { createPassword, updatePassword, deletePassword, getPasswords } from '../api.js'
import PasswordForm from './PasswordForm.jsx'
import './PasswordList.css'

function PasswordCard({ entry, userId, vaultId, onRefresh, addToast }) {
  const [showPassword, setShowPassword] = useState(false)
  const [editing, setEditing] = useState(false)

  async function handleCopy(text, label) {
    try {
      await navigator.clipboard.writeText(text)
      addToast(`${label} copied to clipboard`, 'success')
    } catch {
      addToast('Failed to copy', 'error')
    }
  }

  async function handleDelete() {
    if (!window.confirm(`Delete "${entry.name}"?`)) return
    try {
      await deletePassword(userId, vaultId, entry.id)
      addToast('Password deleted', 'success')
      onRefresh()
    } catch (err) {
      addToast(err.message || 'Failed to delete', 'error')
    }
  }

  async function handleSave(payload) {
    await updatePassword(userId, vaultId, entry.id, payload)
    addToast('Password updated', 'success')
    setEditing(false)
    onRefresh()
  }

  return (
    <>
      <div className="password-card">
        <div className="password-card-header">
          <div className="password-card-title">
            <span className="password-name">{entry.name}</span>
            {entry.tag && (
              <span className="password-tag">
                <MdLabel size={12} />
                {entry.tag}
              </span>
            )}
          </div>
          <div className="password-card-actions">
            <button
              className="btn-icon"
              title="Edit"
              onClick={() => setEditing(true)}
            >
              <MdEdit size={16} />
            </button>
            <button
              className="btn-icon danger-icon"
              title="Delete"
              onClick={handleDelete}
            >
              <MdDelete size={16} />
            </button>
          </div>
        </div>

        <div className="password-card-body">
          {entry.url && (
            <div className="password-field">
              <MdLink size={14} className="field-icon" />
              <a
                href={entry.url}
                target="_blank"
                rel="noopener noreferrer"
                className="field-value field-link"
              >
                {entry.url}
              </a>
            </div>
          )}

          {entry.username && (
            <div className="password-field">
              <MdPerson size={14} className="field-icon" />
              <span className="field-value">{entry.username}</span>
              <button
                className="btn-icon copy-btn"
                title="Copy username"
                onClick={() => handleCopy(entry.username, 'Username')}
              >
                <MdContentCopy size={14} />
              </button>
            </div>
          )}

          <div className="password-field">
            <span className="field-icon field-icon--text">••</span>
            <span className="field-value password-value">
              {showPassword ? entry.password : '••••••••'}
            </span>
            <button
              className="btn-icon"
              title={showPassword ? 'Hide password' : 'Show password'}
              onClick={() => setShowPassword(v => !v)}
            >
              {showPassword ? <MdVisibilityOff size={14} /> : <MdVisibility size={14} />}
            </button>
            <button
              className="btn-icon copy-btn"
              title="Copy password"
              onClick={() => handleCopy(entry.password, 'Password')}
            >
              <MdContentCopy size={14} />
            </button>
          </div>

          {entry.notes && (
            <div className="password-notes">{entry.notes}</div>
          )}
        </div>
      </div>

      {editing && (
        <PasswordForm
          entry={entry}
          onSave={handleSave}
          onClose={() => setEditing(false)}
        />
      )}
    </>
  )
}

export default function PasswordList({ userId, vault, addToast }) {
  const [passwords, setPasswords] = useState([])
  const [loading, setLoading] = useState(false)
  const [adding, setAdding] = useState(false)
  const [refresh, setRefresh] = useState(0)

  useEffect(() => {
    if (!vault) return
    let cancelled = false
    setLoading(true)
    setPasswords([])
    getPasswords(userId, vault.id)
      .then(data => {
        if (!cancelled) setPasswords(Array.isArray(data) ? data : [])
      })
      .catch(err => {
        if (!cancelled) addToast(err.message || 'Failed to load passwords', 'error')
      })
      .finally(() => {
        if (!cancelled) setLoading(false)
      })
    return () => { cancelled = true }
  }, [vault?.id, userId, refresh]) // eslint-disable-line react-hooks/exhaustive-deps

  async function handleAddSave(payload) {
    await createPassword(userId, vault.id, payload)
    addToast('Password created', 'success')
    setAdding(false)
    setRefresh(r => r + 1)
  }

  if (!vault) {
    return (
      <div className="password-list-empty-vault">
        <p>Select a vault to view its passwords</p>
      </div>
    )
  }

  return (
    <div className="password-list">
      <div className="password-list-header">
        <h2>{vault.name}</h2>
        <button
          className="btn btn-primary"
          onClick={() => setAdding(true)}
        >
          <MdAdd size={18} />
          Add Password
        </button>
      </div>

      {loading && (
        <div className="loading-spinner">Loading…</div>
      )}

      {!loading && passwords.length === 0 && (
        <div className="empty-state">
          <MdLabel size={48} style={{ color: 'var(--text-muted)' }} />
          <p>No passwords in this vault yet.</p>
          <p>Click &ldquo;Add Password&rdquo; to get started.</p>
        </div>
      )}

      <div className="password-cards">
        {passwords.map(entry => (
          <PasswordCard
            key={entry.id}
            entry={entry}
            userId={userId}
            vaultId={vault.id}
            onRefresh={() => setRefresh(r => r + 1)}
            addToast={addToast}
          />
        ))}
      </div>

      {adding && (
        <PasswordForm
          entry={null}
          onSave={handleAddSave}
          onClose={() => setAdding(false)}
        />
      )}
    </div>
  )
}
