import { useEffect, useState } from 'react';
import axios from 'axios';

function Employee() {
  const [employees, setEmployees] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [employeeNumber, setEmployeeNumber] = useState('');
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [address, setAddress] = useState('');
  const [position, setPosition] = useState('');
  const [telephone, setTelephone] = useState('');
  const [gender, setGender] = useState('Male');
  const [hiredDate, setHiredDate] = useState('');
  const [department, setDepartment] = useState('');
  const [message, setMessage] = useState('');

  const headers = { Authorization: `Bearer ${localStorage.getItem('token')}` };

  const getEmployees = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/employees/list', { headers });
      setEmployees(res.data);
    } catch (err) {
      console.error(err);
    }
  };

  const getDepartments = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/departments/list', { headers });
      setDepartments(res.data);
    } catch (err) {
      console.error(err);
    }
  };

  useEffect(() => {
    getEmployees();
    getDepartments();
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await axios.post(
        'http://localhost:5001/api/employees/add',
        { employeeNumber, firstName, lastName, address, position, telephone, gender, hiredDate, department },
        { headers }
      );
      setMessage('Employee added successfully');
      setEmployeeNumber('');
      setFirstName('');
      setLastName('');
      setAddress('');
      setPosition('');
      setTelephone('');
      setGender('Male');
      setHiredDate('');
      setDepartment('');
      getEmployees();
    } catch (err) {
      setMessage(err.response?.data?.message || 'Failed to add employee');
    }
  };

  const isSuccess = message.includes('successfully');

  return (
    <div>
      <h1 className="mb-6 text-2xl font-bold">Employee Management</h1>

      {message && (
        <p className={isSuccess ? 'alert-success' : 'alert-error'}>{message}</p>
      )}

      <form onSubmit={handleSubmit} className="mb-6 box space-y-4">
        <h2 className="font-semibold">Add Employee</h2>
        <div className="grid gap-4 sm:grid-cols-2">
          <div>
            <label className="mb-1 block text-sm">Employee Number</label>
            <input type="text" value={employeeNumber} onChange={(e) => setEmployeeNumber(e.target.value)} className="input-field" required />
          </div>
          <div>
            <label className="mb-1 block text-sm">First Name</label>
            <input type="text" value={firstName} onChange={(e) => setFirstName(e.target.value)} className="input-field" required />
          </div>
          <div>
            <label className="mb-1 block text-sm">Last Name</label>
            <input type="text" value={lastName} onChange={(e) => setLastName(e.target.value)} className="input-field" required />
          </div>
          <div>
            <label className="mb-1 block text-sm">Telephone</label>
            <input type="tel" value={telephone} onChange={(e) => setTelephone(e.target.value)} className="input-field" required />
          </div>
          <div>
            <label className="mb-1 block text-sm">Position</label>
            <input type="text" value={position} onChange={(e) => setPosition(e.target.value)} className="input-field" required />
          </div>
          <div>
            <label className="mb-1 block text-sm">Gender</label>
            <select value={gender} onChange={(e) => setGender(e.target.value)} className="input-field">
              <option value="Male">Male</option>
              <option value="Female">Female</option>
              <option value="Other">Other</option>
            </select>
          </div>
          <div className="sm:col-span-2">
            <label className="mb-1 block text-sm">Address</label>
            <input type="text" value={address} onChange={(e) => setAddress(e.target.value)} className="input-field" required />
          </div>
          <div>
            <label className="mb-1 block text-sm">Hired Date</label>
            <input type="date" value={hiredDate} onChange={(e) => setHiredDate(e.target.value)} className="input-field" required />
          </div>
          <div>
            <label className="mb-1 block text-sm">Department</label>
            <select value={department} onChange={(e) => setDepartment(e.target.value)} className="input-field" required>
              <option value="">Select department</option>
              {departments.map((dept) => (
                <option key={dept._id} value={dept._id}>{dept.departmentName}</option>
              ))}
            </select>
          </div>
        </div>
        <button type="submit" className="btn-primary">Add Employee</button>
      </form>

      <div className="box">
        <h2 className="mb-3 font-semibold">Employee List ({employees.length})</h2>
        {employees.length === 0 ? (
          <p className="text-gray-600">No employees yet.</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="data-table">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Number</th>
                  <th>Department</th>
                  <th>Position</th>
                  <th>Phone</th>
                </tr>
              </thead>
              <tbody>
                {employees.map((emp) => (
                  <tr key={emp._id}>
                    <td>{emp.firstName} {emp.lastName}</td>
                    <td>{emp.employeeNumber}</td>
                    <td>{emp.department?.departmentName || 'N/A'}</td>
                    <td>{emp.position}</td>
                    <td>{emp.telephone}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

export default Employee;
