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

function EmployeeList({ user }) {
  const [employees, setEmployees] = useState([])
  const [search, setSearch] = useState('')
  const [loading, setLoading] = useState(true)

  useEffect(() => { fetchEmployees() }, [])

  const fetchEmployees = async (query) => {
    try {
      setLoading(true)
      const res = query ? await employeeAPI.search(query) : await employeeAPI.getAll()
      setEmployees(res.data)
    } catch (error) {
      console.error('Failed to fetch employees:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleSearch = (e) => {
    e.preventDefault()
    fetchEmployees(search)
  }

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this employee?')) return
    try {
      await employeeAPI.remove(id)
      setEmployees(employees.filter(e => e._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">Employees</h1>
          <p className="page-subtitle">{employees.length} employee(s)</p>
        </div>
        {user?.role === 'admin' && (
          <Link to="/employees/add" className="btn btn-teal">Add Employee</Link>
        )}
      </div>

      <div className="card">
        <div className="p-4 border-b border-slate-200">
          <form onSubmit={handleSearch} className="flex gap-2">
            <input type="text" className="input max-w-xs" placeholder="Search..."
              value={search} onChange={(e) => setSearch(e.target.value)} />
            <button type="submit" className="btn btn-teal text-xs">Search</button>
            {search && <button type="button" onClick={() => { setSearch(''); fetchEmployees() }} className="btn btn-ghost text-xs">Clear</button>}
          </form>
        </div>

        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="bg-slate-50">
                <th className="table-header">Name</th>
                <th className="table-header">Gender</th>
                <th className="table-header">Contact</th>
                <th className="table-header">Department</th>
                <th className="table-header">Position</th>
                <th className="table-header">Status</th>
                <th className="table-header text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-200">
              {loading ? (
                [...Array(5)].map((_, i) => (
                  <tr key={i} className="animate-pulse">
                    {[...Array(7)].map((_, j) => <td key={j} className="table-cell"><div className="h-4 bg-slate-200 rounded w-3/4"></div></td>)}
                  </tr>
                ))
              ) : employees.length === 0 ? (
                <tr><td colSpan={7} className="table-cell text-center text-slate-400 py-8">No employees found</td></tr>
              ) : (
                employees.map(emp => (
                  <tr key={emp._id}>
                    <td className="table-cell font-medium text-slate-900">{emp.EmpFirstName} {emp.EmpLastName}</td>
                    <td className="table-cell">{emp.EmpGender}</td>
                    <td className="table-cell">{emp.EmpTelephone}<br /><span className="text-xs text-slate-400">{emp.EmpEmail}</span></td>
                    <td className="table-cell">{emp.Department?.DepartName || '—'}</td>
                    <td className="table-cell">{emp.Position?.PosName || '—'}</td>
                    <td className="table-cell">
                      <span className={`badge ${
                        emp.EmpStatus === 'Active' ? 'bg-teal-50 text-teal-700 border-teal-200' :
                        emp.EmpStatus === 'On Leave' ? 'bg-amber-50 text-amber-700 border-amber-200' :
                        emp.EmpStatus === 'On Mission' ? 'bg-cyan-50 text-cyan-700 border-cyan-200' :
                        'bg-slate-100 text-slate-600 border-slate-200'
                      }`}>{emp.EmpStatus}</span>
                    </td>
                    <td className="table-cell text-right">
                      {user?.role === 'admin' ? (
                        <>
                          <Link to={`/employees/edit/${emp._id}`} className="btn btn-ghost text-xs mr-1">Edit</Link>
                          <button onClick={() => handleDelete(emp._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>
    </div>
  )
}

export default EmployeeList
