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

function UserList() {
  const [users, setUsers] = useState([])
  const [loading, setLoading] = useState(true)

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

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this user?')) return
    try {
      await userAPI.remove(id)
      setUsers(users.filter(u => u._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">Users</h1>
          <p className="page-subtitle">{users.length} user account(s)</p>
        </div>
        <Link to="/users/add" className="btn btn-teal">Add User</Link>
      </div>

      <div className="card overflow-hidden">
        <table className="w-full">
          <thead>
            <tr className="bg-slate-50">
              <th className="table-header">Username</th>
              <th className="table-header">Employee</th>
              <th className="table-header text-right">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-slate-200">
            {loading ? (
              [...Array(3)].map((_, i) => (
                <tr key={i} className="animate-pulse">
                  <td className="table-cell"><div className="h-4 bg-slate-200 rounded w-1/3"></div></td>
                  <td className="table-cell"><div className="h-4 bg-slate-200 rounded w-1/2"></div></td>
                  <td className="table-cell"><div className="h-4 bg-slate-200 rounded w-16 ml-auto"></div></td>
                </tr>
              ))
            ) : users.length === 0 ? (
              <tr><td colSpan={3} className="table-cell text-center text-slate-400 py-8">No users found.</td></tr>
            ) : (
              users.map(u => (
                <tr key={u._id}>
                  <td className="table-cell font-medium text-slate-900">{u.UserName}</td>
                  <td className="table-cell text-slate-500">{u.Employee ? `${u.Employee.EmpFirstName} ${u.Employee.EmpLastName}` : 'N/A'}</td>
                  <td className="table-cell text-right">
                    <Link to={`/users/edit/${u._id}`} className="btn btn-ghost text-xs mr-1">Edit</Link>
                    <button onClick={() => handleDelete(u._id)} className="btn btn-red text-xs">Delete</button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}

export default UserList
