import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import type { Employee } from '@skillmate/shared'
import { api } from '../services/api'

export default function EmployeeManagement() {
  const navigate = useNavigate()
  const [employees, setEmployees] = useState<Employee[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')

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

  const fetchEmployees = async () => {
    try {
      const response = await api.get('/employees')
      setEmployees(response.data.data)
    } catch (error) {
      console.error('Failed to fetch employees:', error)
    } finally {
      setLoading(false)
    }
  }

  const filteredEmployees = employees.filter(emp =>
    `${emp.firstName} ${emp.lastName}`.toLowerCase().includes(searchTerm.toLowerCase()) ||
    emp.employeeNumber.toLowerCase().includes(searchTerm.toLowerCase()) ||
    emp.department.toLowerCase().includes(searchTerm.toLowerCase())
  )

  if (loading) {
    return (
      <div className="flex items-center justify-center h-full">
        <p className="text-tertiary">Mitarbeitende werden geladen...</p>
      </div>
    )
  }

  return (
    <div>
      <div className="flex justify-between items-center mb-8">
        <h1 className="text-title-lg font-poppins font-bold text-primary">
          Mitarbeitendenverwaltung
        </h1>
        <button
          onClick={() => navigate('/employees/new')}
          className="btn-primary"
        >
          Neues Mitarbeitendenprofil
        </button>
      </div>

      <div className="card mb-6">
        <input
          type="text"
          placeholder="Suche nach Name, Personalnummer oder Abteilung..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="input-field w-full"
        />
      </div>

      <div className="card">
        <div className="overflow-x-auto">
          <table className="w-full">
            <thead>
              <tr className="table-header">
                <th className="px-4 py-3 text-left">Personalnr.</th>
                <th className="px-4 py-3 text-left">Name</th>
                <th className="px-4 py-3 text-left">Position</th>
                <th className="px-4 py-3 text-left">Abteilung</th>
                <th className="px-4 py-3 text-left">Status</th>
                <th className="px-4 py-3 text-left">Aktionen</th>
              </tr>
            </thead>
            <tbody>
              {filteredEmployees.map((employee) => (
                <tr key={employee.id} className="table-row">
                  <td className="px-4 py-3">{employee.employeeNumber}</td>
                  <td className="px-4 py-3">
                    {employee.firstName} {employee.lastName}
                  </td>
                  <td className="px-4 py-3">{employee.position}</td>
                  <td className="px-4 py-3">{employee.department}</td>
                  <td className="px-4 py-3">
                    <span className={`badge ${
                      employee.availability === 'available' ? 'badge-success' : 'badge-warning'
                    }`}>
                      {employee.availability}
                    </span>
                  </td>
                  <td className="px-4 py-3">
                    <button
                      onClick={() => navigate(`/employees/${employee.id}/edit`)}
                      className="text-primary-blue hover:text-primary-blue-hover mr-3"
                    >
                      Bearbeiten
                    </button>
                    <button className="text-error hover:text-error/80">
                      Löschen
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {filteredEmployees.length === 0 && (
          <div className="text-center py-8">
            <p className="text-tertiary">Keine Mitarbeitenden gefunden</p>
          </div>
        )}
      </div>
    </div>
  )
}
