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

function PositionList({ user }) {
  const [positions, setPositions] = useState([])
  const [loading, setLoading] = useState(true)

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

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this position?')) return
    try {
      await positionAPI.remove(id)
      setPositions(positions.filter(p => p._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">Positions</h1>
          <p className="page-subtitle">{positions.length} position(s)</p>
        </div>
        {user?.role === 'admin' && (
          <Link to="/positions/add" className="btn btn-amber">Add Position</Link>
        )}
      </div>

      <div className="card overflow-hidden">
        <table className="w-full">
          <thead>
            <tr className="bg-slate-50">
              <th className="table-header">Position</th>
              <th className="table-header">Qualification</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-2/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>
              ))
            ) : positions.length === 0 ? (
              <tr><td colSpan={3} className="table-cell text-center text-slate-400 py-8">No positions found.</td></tr>
            ) : (
              positions.map(p => (
                <tr key={p._id}>
                  <td className="table-cell font-medium text-slate-900">{p.PosName}</td>
                  <td className="table-cell text-slate-500">{p.RequiredQualification || 'N/A'}</td>
                  <td className="table-cell text-right">
                    {user?.role === 'admin' ? (
                      <>
                        <Link to={`/positions/edit/${p._id}`} className="btn btn-ghost text-xs mr-1">Edit</Link>
                        <button onClick={() => handleDelete(p._id)} className="btn btn-red text-xs">Delete</button>
                      </>
                    ) : (
                      <span className="text-xs text-slate-400">Read only</span>
                    )}
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  )
}

export default PositionList
