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

function Department() {
  const [departments, setDepartments] = useState([]);
  const [departmentCode, setDepartmentCode] = useState('');
  const [departmentName, setDepartmentName] = useState('');
  const [message, setMessage] = useState('');

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

  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(() => {
    getDepartments();
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await axios.post(
        'http://localhost:5001/api/departments/add',
        { departmentCode, departmentName },
        { headers }
      );
      setMessage('Department added successfully');
      setDepartmentCode('');
      setDepartmentName('');
      getDepartments();
    } catch (err) {
      setMessage(err.response?.data?.message || 'Failed to add department');
    }
  };

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

      <form onSubmit={handleSubmit} className="mb-6 box space-y-4">
        <h2 className="font-semibold">Add Department</h2>
        <div>
          <label className="mb-1 block text-sm">Department Code</label>
          <input
            type="text"
            value={departmentCode}
            onChange={(e) => setDepartmentCode(e.target.value)}
            className="input-field"
            required
          />
        </div>
        <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"
            required
          />
        </div>
        <button type="submit" className="btn-primary">Add Department</button>
      </form>

      <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>
        ) : (
          <table className="data-table">
            <thead>
              <tr>
                <th>Code</th>
                <th>Name</th>
              </tr>
            </thead>
            <tbody>
              {departments.map((dept) => (
                <tr key={dept._id}>
                  <td>{dept.departmentCode}</td>
                  <td>{dept.departmentName}</td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
}

export default Department;
