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

function Position() {
  const [positions, setPositions] = useState([]);
  const [posName, setPosName] = useState('');
  const [requiredQualification, setRequiredQualification] = useState('');
  const [editingId, setEditingId] = useState(null);
  const [message, setMessage] = useState('');
  const currentUser = JSON.parse(localStorage.getItem('user') || 'null');

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

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editingId) {
        await axios.put(
          `/api/positions/${editingId}`,
          { posName, requiredQualification },
          { withCredentials: true }
        );
        setMessage('Position updated successfully');
      } else {
        await axios.post(
          '/api/positions/add',
          { posName, requiredQualification },
          { withCredentials: true }
        );
        setMessage('Position added successfully');
      }

      setPosName('');
      setRequiredQualification('');
      setEditingId(null);
      getPositions();
    } catch (err) {
      setMessage(err.response?.data?.message || 'Failed to save position');
    }
  };

  const handleEdit = (position) => {
    setPosName(position.posName);
    setRequiredQualification(position.requiredQualification);
    setEditingId(position._id);
    setMessage('');
  };

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

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

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

  return (
    <div>
      <h1 className="mb-6 text-2xl font-bold">Position 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 Position' : 'Add Position'}</h2>
        <div>
          <label className="mb-1 block text-sm">Position Name</label>
          <input
            type="text"
            value={posName}
            onChange={(e) => setPosName(e.target.value)}
            className="input-field"
            placeholder="e.g. Software Engineer"
            required
          />
        </div>
        <div>
          <label className="mb-1 block text-sm">Required Qualification</label>
          <input
            type="text"
            value={requiredQualification}
            onChange={(e) => setRequiredQualification(e.target.value)}
            className="input-field"
            placeholder="e.g. Bachelor’s in Computer Science"
            required
          />
        </div>
        <div className="flex items-center gap-3">
          <button type="submit" className="btn-primary">
            {editingId ? 'Update Position' : 'Add Position'}
          </button>
          {editingId && (
            <button type="button" className="btn-secondary" onClick={handleCancel}>
              Cancel
            </button>
          )}
        </div>
        </form>
      ) : (
        <div className="mb-6 box">
          <h2 className="font-semibold">Positions (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">Position List ({positions.length})</h2>
        {positions.length === 0 ? (
          <p className="text-gray-600">No positions yet.</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="data-table">
              <thead>
                <tr>
                  <th>Position</th>
                  <th>Qualification</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {positions.map((pos) => (
                  <tr key={pos._id}>
                    <td>{pos.posName}</td>
                    <td>{pos.requiredQualification}</td>
                    <td className="space-x-2">
                      {currentUser?.role === 'admin' && (
                        <>
                          <button type="button" className="btn-secondary btn-small" onClick={() => handleEdit(pos)}>
                            Edit
                          </button>
                          <button type="button" className="btn-danger btn-small" onClick={() => handleDelete(pos._id)}>
                            Delete
                          </button>
                        </>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

export default Position;


