import { useEffect, useMemo, useState } from 'react'
import api from '../api/axios'
import Loading from '../components/Loading'

export default function Dashboard() {
  const [stats, setStats] = useState({ employees: 0, departments: 0, salaries: 0 })
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)

  useEffect(() => {
    const load = async () => {
      try {
        setLoading(true)
        setError(null)
        const [employeesRes, departmentsRes, salariesRes] = await Promise.all([
          api.get('/employees'),
          api.get('/departments'),
          api.get('/salaries')
        ])
        setStats({
          employees: (employeesRes.data || []).length,
          departments: (departmentsRes.data || []).length,
          salaries: (salariesRes.data || []).length
        })
      } catch (err) {
        setError(err.message)
      } finally {
        setLoading(false)
      }
    }
    load()
  }, [])

  const cards = useMemo(
    () => [
      { label: 'Total Employees', value: stats.employees, color: 'bg-indigo-600' },
      { label: 'Total Departments', value: stats.departments, color: 'bg-emerald-600' },
      { label: 'Total Salaries', value: stats.salaries, color: 'bg-sky-600' }
    ],
    [stats]
  )

  return (
    <div>
      <div className="mb-5">
        <h1 className="text-2xl font-bold text-slate-900">Dashboard</h1>
        <p className="mt-1 text-sm text-slate-500">Overview of EPMS records.</p>
      </div>

      {loading ? (
        <Loading label="Loading statistics" />
      ) : error ? (
        <div className="rounded-lg bg-red-50 p-4 text-sm text-red-700">{error}</div>
      ) : (
        <div className="grid gap-4 md:grid-cols-3">
          {cards.map((c) => (
            <div key={c.label} className="rounded-2xl bg-white p-5 shadow-sm ring-1 ring-slate-200">
              <div className={`h-10 w-10 rounded-xl ${c.color} p-0.5`} />
              <div className="mt-3 text-sm text-slate-600">{c.label}</div>
              <div className="mt-2 text-3xl font-extrabold text-slate-900">{c.value}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

