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

const EMPLOYEE_STATUSES = ['on leave', 'left', 'blacklisted', 'deceased', 'on mission'];

function Employee() {
  const [employees, setEmployees] = useState([]);
  const [departments, setDepartments] = useState([]);
  const [positions, setPositions] = useState([]);
  const [editingId, setEditingId] = useState(null);
  const [userName, setUserName] = useState('');
  const [firstName, setFirstName] = useState('');
  const [lastName, setLastName] = useState('');
  const [email, setEmail] = useState('');
  const [address, setAddress] = useState('');
  const [position, setPosition] = useState('');
  const [telephone, setTelephone] = useState('');
  const [gender, setGender] = useState('Male');
  const [dateOfBirth, setDateOfBirth] = useState('');
  const [hireDate, setHireDate] = useState('');
  const [status, setStatus] = useState('on mission');
  const [department, setDepartment] = useState('');
  const [message, setMessage] = useState('');
  const currentUser = JSON.parse(localStorage.getItem('user') || 'null');

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

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

  const getPositions = async () => {
    try {
      const res = await axios.get('/api/positions/list', { withCredentials: true });
      setPositions(res.data);
    } catch (err) {
      console.error(err);
    }
  };

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

  const resetForm = () => {
    setEditingId(null);
    setUserName('');
    setFirstName('');
    setLastName('');
    setEmail('');
    setAddress('');
    setPosition('');
    setTelephone('');
    setGender('Male');
    setDateOfBirth('');
    setHireDate('');
    setStatus('on mission');
    setDepartment('');
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const payload = {
        userName,
        firstName,
        lastName,
        email,
        gender,
        dateOfBirth,
        telephone,
        address,
        hireDate,
        status,
        department,
        position,
      };

      if (editingId) {
        await axios.put(`/api/employees/${editingId}`, payload, { withCredentials: true });
        setMessage('Employee updated successfully');
      } else {
        await axios.post('/api/employees/add', payload, { withCredentials: true });
        setMessage('Employee added successfully');
      }

      resetForm();
      getEmployees();
    } catch (err) {
      setMessage(err.response?.data?.message || 'Failed to save employee');
    }
  };

  const handleEdit = (emp) => {
    setEditingId(emp._id);
    setUserName(emp.userName || '');
    setFirstName(emp.firstName);
    setLastName(emp.lastName);
    setEmail(emp.email);
    setAddress(emp.address);
    setPosition(emp.position?._id || '');
    setTelephone(emp.telephone);
    setGender(emp.gender);
    setDateOfBirth(emp.dateOfBirth ? emp.dateOfBirth.split('T')[0] : '');
    setHireDate(emp.hireDate ? emp.hireDate.split('T')[0] : '');
    setStatus(EMPLOYEE_STATUSES.includes(emp.status) ? emp.status : 'on mission');
    setDepartment(emp.department?._id || '');
    setMessage('');
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this employee?')) return;
    try {
      await axios.delete(`/api/employees/${id}`, { withCredentials: true });
      setMessage('Employee deleted successfully');
      if (editingId === id) {
        resetForm();
      }
      getEmployees();
    } catch (err) {
      setMessage(err.response?.data?.message || 'Failed to delete employee');
    }
  };

  const handleCancel = () => {
    resetForm();
    setMessage('');
  };

  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>
      )}

      {currentUser?.role === 'admin' ? (
        <form onSubmit={handleSubmit} className="mb-6 box space-y-4">
        <h2 className="font-semibold">{editingId ? 'Edit Employee' : 'Add Employee'}</h2>
        <div className="grid gap-4 sm:grid-cols-2">
          <div>
            <label className="mb-1 block text-sm">Username (optional)</label>
            <input
              type="text"
              value={userName}
              onChange={(e) => setUserName(e.target.value)}
              className="input-field"
              placeholder="Optional user handle"
            />
          </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"
              placeholder="Enter first name"
              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"
              placeholder="Enter last name"
              required
            />
          </div>
          <div>
            <label className="mb-1 block text-sm">Email</label>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="input-field"
              placeholder="Enter employee email"
              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"
              placeholder="Enter phone number"
              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>
            <label className="mb-1 block text-sm">Position</label>
            <select
              value={position}
              onChange={(e) => setPosition(e.target.value)}
              className="input-field"
              required
            >
              <option value="">Select position</option>
              {positions.map((pos) => (
                <option key={pos._id} value={pos._id}>{pos.posName}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="mb-1 block text-sm">Status</label>
            <select
              value={status}
              onChange={(e) => setStatus(e.target.value)}
              className="input-field"
              required
            >
              {EMPLOYEE_STATUSES.map((s) => (
                <option key={s} value={s}>{s}</option>
              ))}
            </select>
          </div>
          <div>
            <label className="mb-1 block text-sm">Date of Birth</label>
            <input
              type="date"
              value={dateOfBirth}
              onChange={(e) => setDateOfBirth(e.target.value)}
              className="input-field"
              required
            />
          </div>
          <div>
            <label className="mb-1 block text-sm">Hire Date</label>
            <input
              type="date"
              value={hireDate}
              onChange={(e) => setHireDate(e.target.value)}
              className="input-field"
              required
            />
          </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"
              placeholder="Enter employee address"
              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>
        <div className="flex items-center gap-3">
          <button type="submit" className="btn-primary">
            {editingId ? 'Update Employee' : 'Add Employee'}
          </button>
          {editingId && (
            <button type="button" className="btn-secondary" onClick={handleCancel}>
              Cancel
            </button>
          )}
        </div>
        </form>
      ) : (
        <div className="mb-6 box">
          <h2 className="font-semibold">Employees (read-only)</h2>
          <p className="text-sm text-gray-600">You have read-only access. Contact an admin for changes.</p>
        </div>
      )}

      <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>Username</th>
                  <th>Name</th>
                  <th>Email</th>
                  <th>Telephone</th>
                  <th>Address</th>
                  <th>Gender</th>
                  <th>DOB</th>
                  <th>Hire Date</th>
                  <th>Department</th>
                  <th>Position</th>
                  <th>Status</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {employees.map((emp) => (
                  <tr key={emp._id}>
                    <td>{emp.userName || 'N/A'}</td>
                    <td>{emp.firstName} {emp.lastName}</td>
                    <td>{emp.email}</td>
                    <td>{emp.telephone}</td>
                    <td>{emp.address}</td>
                    <td>{emp.gender}</td>
                    <td>{emp.dateOfBirth ? emp.dateOfBirth.split('T')[0] : 'N/A'}</td>
                    <td>{emp.hireDate ? emp.hireDate.split('T')[0] : 'N/A'}</td>
                    <td>{emp.department?.departmentName || 'N/A'}</td>
                    <td>{emp.position?.posName || 'N/A'}</td>
                    <td className="capitalize">{emp.status}</td>
                    <td className="space-x-2">
                      {currentUser?.role === 'admin' && (
                        <>
                          <button type="button" className="btn-secondary btn-small" onClick={() => handleEdit(emp)}>
                            Edit
                          </button>
                          <button type="button" className="btn-danger btn-small" onClick={() => handleDelete(emp._id)}>
                            Delete
                          </button>
                        </>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

export default Employee;


