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

function Department() {
  const [departments, setDepartments] = useState([]);
  const [departmentName, setDepartmentName] = useState('');
  const [editingId, setEditingId] = useState(null);
  const [message, setMessage] = useState('');
  const currentUser = JSON.parse(localStorage.getItem('user') || 'null');

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

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editingId) {
        await axios.put(
          `/api/departments/${editingId}`,
          { departmentName },
          { withCredentials: true }
        );
        setMessage('Department updated successfully');
      } else {
        await axios.post(
          '/api/departments/add',
          { departmentName },
          { withCredentials: true }
        );
        setMessage('Department added successfully');
      }
      setDepartmentName('');
      setEditingId(null);
      getDepartments();
    } catch (err) {
      setMessage(err.response?.data?.message || 'Failed to save department');
    }
  };

  const handleEdit = (department) => {
    setDepartmentName(department.departmentName);
    setEditingId(department._id);
    setMessage('');
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this department?')) return;
    try {
      await axios.delete(`/api/departments/${id}`, { withCredentials: true });
      setMessage('Department deleted successfully');
      if (editingId === id) {
        setEditingId(null);
        setDepartmentName('');
      }
      getDepartments();
    } catch (err) {
      setMessage(err.response?.data?.message || 'Failed to delete department');
    }
  };

  const handleCancel = () => {
    setEditingId(null);
    setDepartmentName('');
    setMessage('');
  };

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

  return (
    <div>
      <h1 className="mb-6 text-2xl font-bold">Department 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 Department' : 'Add Department'}</h2>
          <div>
            <label className="mb-1 block text-sm">Department Name</label>
            <input
              type="text"
              value={departmentName}
              onChange={(e) => setDepartmentName(e.target.value)}
              className="input-field"
              placeholder="e.g. Human Resources"
              required
            />
          </div>
          <div className="flex items-center gap-3">
            <button type="submit" className="btn-primary">
              {editingId ? 'Update Department' : 'Add Department'}
            </button>
            {editingId && (
              <button type="button" className="btn-secondary" onClick={handleCancel}>
                Cancel
              </button>
            )}
          </div>
        </form>
      ) : (
        <div className="mb-6 box">
          <h2 className="font-semibold">Departments (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">Department List ({departments.length})</h2>
        {departments.length === 0 ? (
          <p className="text-gray-600">No departments yet.</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="data-table">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {departments.map((dept) => (
                  <tr key={dept._id}>
                    <td>{dept.departmentName}</td>
                    <td className="space-x-2">
                      {currentUser?.role === 'admin' && (
                        <>
                          <button type="button" className="btn-secondary btn-small" onClick={() => handleEdit(dept)}>
                            Edit
                          </button>
                          <button type="button" className="btn-danger btn-small" onClick={() => handleDelete(dept._id)}>
                            Delete
                          </button>
                        </>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

export default Department;


