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

function DepartmentList({ user }) {
  const [departments, setDepartments] = useState([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    departmentAPI.getAll().then(res => setDepartments(res.data)).catch(console.error).finally(() => setLoading(false))
  }, [])

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this department?')) return
    try {
      await departmentAPI.remove(id)
      setDepartments(departments.filter(d => d._id !== id))
    } catch (error) {
      alert(error.response?.data?.message || 'Failed to delete')
    }
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="page-title">Departments</h1>
          <p className="page-subtitle">{departments.length} department(s)</p>
        </div>
        {user?.role === 'admin' && (
          <Link to="/departments/add" className="btn btn-teal">Add Department</Link>
        )}
      </div>

      {loading ? (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {[...Array(3)].map((_, i) => <div key={i} className="card p-4 animate-pulse"><div className="h-4 bg-slate-200 rounded w-2/3"></div></div>)}
        </div>
      ) : departments.length === 0 ? (
        <div className="card p-8 text-center text-slate-400">No departments found.</div>
      ) : (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {departments.map(d => (
            <div key={d._id} className="card p-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="font-semibold text-slate-900">{d.DepartName}</p>
                  <p className="text-xs text-slate-400">Department</p>
                </div>
              </div>
              <div className="mt-3 pt-3 border-t border-slate-200 flex gap-2">
                {user?.role === 'admin' ? (
                  <>
                    <Link to={`/departments/edit/${d._id}`} className="btn btn-ghost text-xs">Edit</Link>
                    <button onClick={() => handleDelete(d._id)} className="btn btn-red text-xs">Delete</button>
                  </>
                ) : (
                  <span className="text-xs text-slate-400">Read only</span>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  )
}

export default DepartmentList
