import { useState, useEffect, useCallback } from 'react'
import { useNavigate } from 'react-router-dom'
import { MdLock, MdLogout } from 'react-icons/md'
import { getVaults } from '../api.js'
import { clearMasterPassword } from '../masterKey.js'
import VaultList from './VaultList.jsx'
import PasswordList from './PasswordList.jsx'
import Toast, { useToast } from './Toast.jsx'
import './Dashboard.css'

export default function Dashboard() {
  const [vaults, setVaults] = useState([])
  const [selectedVault, setSelectedVault] = useState(null)
  const [loadingVaults, setLoadingVaults] = useState(false)
  const { toasts, addToast } = useToast()
  const navigate = useNavigate()

  const userId = localStorage.getItem('userId')
  const username = localStorage.getItem('username')

  const fetchVaults = useCallback(async () => {
    if (!userId) return
    setLoadingVaults(true)
    try {
      const data = await getVaults(userId)
      const list = Array.isArray(data) ? data : []
      setVaults(list)
      // Keep selected vault in sync after refresh
      setSelectedVault(prev => {
        if (!prev) return null
        return list.find(v => v.id === prev.id) || null
      })
    } catch (err) {
      addToast(err.message || 'Failed to load vaults', 'error')
    } finally {
      setLoadingVaults(false)
    }
  }, [userId, addToast])

  useEffect(() => {
    fetchVaults()
  }, [fetchVaults])

  function handleLogout() {
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
    localStorage.removeItem('userId')
    localStorage.removeItem('username')
    clearMasterPassword()
    navigate('/login', { replace: true })
  }

  return (
    <div className="dashboard">
      {/* Header / Navbar */}
      <header className="dashboard-header">
        <div className="header-brand">
          <MdLock className="header-lock-icon" />
          <span className="header-title">Password Manager</span>
        </div>
        <div className="header-right">
          {username && (
            <span className="header-username">{username}</span>
          )}
          <button className="btn btn-secondary logout-btn" onClick={handleLogout}>
            <MdLogout size={16} />
            Logout
          </button>
        </div>
      </header>

      {/* Main layout */}
      <div className="dashboard-body">
        {/* Sidebar */}
        <aside className="dashboard-sidebar">
          {loadingVaults ? (
            <div className="loading-spinner">Loading…</div>
          ) : (
            <VaultList
              userId={userId}
              vaults={vaults}
              selectedVaultId={selectedVault?.id}
              onSelect={setSelectedVault}
              onRefresh={fetchVaults}
              addToast={addToast}
            />
          )}
        </aside>

        {/* Main content */}
        <main className="dashboard-main">
          <PasswordList
            userId={userId}
            vault={selectedVault}
            addToast={addToast}
          />
        </main>
      </div>

      <Toast toasts={toasts} />
    </div>
  )
}
