import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { employeeAPI, departmentAPI, positionAPI, userAPI } from '../services/api'

function Dashboard({ user }) {
  const [stats, setStats] = useState({ employees: 0, departments: 0, positions: 0, users: 0 })

  useEffect(() => {
    const fetchStats = async () => {
      try {
        const promises = [employeeAPI.getAll(), departmentAPI.getAll(), positionAPI.getAll()]
        if (user?.role === 'admin') promises.push(userAPI.getAll())
        const [empRes, depRes, posRes, userRes] = await Promise.all(promises)
        setStats({
          employees: empRes.data.length,
          departments: depRes.data.length,
          positions: posRes.data.length,
          users: userRes ? userRes.data.length : 0
        })
      } catch (error) {
        console.error('Failed to fetch stats:', error)
      }
    }
    fetchStats()
  }, [user])

  const cards = [
    { label: 'Employees', count: stats.employees, link: '/employees' },
    { label: 'Departments', count: stats.departments, link: '/departments' },
    { label: 'Positions', count: stats.positions, link: '/positions' }
  ]

  if (user?.role === 'admin') {
    cards.push({ label: 'Users', count: stats.users, link: '/users' })
  }

  return (
    <div className="space-y-6">
      <div>
        <h1 className="page-title">Dashboard</h1>
        <p className="page-subtitle">Overview of your HRMS system</p>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {cards.map(card => (
          <Link key={card.label} to={card.link} className="card p-4">
            <p className="text-2xl font-bold text-slate-900">{card.count}</p>
            <p className="text-sm text-slate-500">{card.label}</p>
          </Link>
        ))}
      </div>

      <div className="card p-4">
        <p className="card-title mb-3">Quick Actions</p>
        <div className="flex flex-wrap gap-2">
          <Link to="/employees" className="btn btn-teal text-xs">View Employees</Link>
          <Link to="/departments" className="btn btn-teal text-xs">View Departments</Link>
          <Link to="/positions" className="btn btn-amber text-xs">View Positions</Link>
          {user?.role === 'admin' && (
            <>
              <Link to="/employees/add" className="btn btn-teal text-xs">Add Employee</Link>
              <Link to="/departments/add" className="btn btn-teal text-xs">Add Department</Link>
              <Link to="/positions/add" className="btn btn-amber text-xs">Add Position</Link>
              <Link to="/users/add" className="btn btn-teal text-xs">Add User</Link>
              <Link to="/status-report" className="btn btn-ghost text-xs">Status Report</Link>
            </>
          )}
        </div>
      </div>
    </div>
  )
}

export default Dashboard
