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

/* =====================
   Constants
===================== */
const API_BASE = process.env.REACT_APP_API_BASE_URL;

const AdminHR = () => {
  const [submissions, setSubmissions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  /* =====================
     Fetch Submissions
  ===================== */
  const fetchSubmissions = async () => {
    try {
      setLoading(true);
      setError(null);

      const res = await axios.get(`${API_BASE}/api/hr-submissions`);
      setSubmissions(res.data || []);
    } catch (err) {
      console.error('Error fetching HR submissions:', err);
      setError('Failed to load submissions');
    } finally {
      setLoading(false);
    }
  };

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

  /* =====================
     Delete Submission
  ===================== */
  const handleDelete = async (id) => {
    if (!window.confirm('Are you sure you want to delete this submission?')) return;

    try {
      await axios.delete(`${API_BASE}/api/hr-submissions/${id}`);
      setSubmissions((prev) => prev.filter((sub) => sub.id !== id));
    } catch (err) {
      console.error('Error deleting submission:', err);
      alert('Failed to delete submission');
    }
  };

  return (
    <div className="max-w-6xl mx-auto px-4 py-16">
      <h2 className="text-3xl font-bold text-blue-900 mb-4">Admin - HR</h2>
      <p className="text-gray-600 mb-6">
        Manage HR contacts and career submissions.
      </p>

      {/* STATES */}
      {loading && <p className="text-gray-500">Loading submissions...</p>}

      {!loading && error && (
        <p className="text-red-600">{error}</p>
      )}

      {!loading && !error && submissions.length === 0 && (
        <p className="text-gray-500">No submissions found.</p>
      )}

      {!loading && !error && submissions.length > 0 && (
        <div className="overflow-x-auto">
          <table className="w-full border-collapse border border-gray-200">
            <thead>
              <tr className="bg-blue-100 text-left">
                <th className="p-2 border">ID</th>
                <th className="p-2 border">Name</th>
                <th className="p-2 border">Email</th>
                <th className="p-2 border">Phone</th>
                <th className="p-2 border">Resume</th>
                <th className="p-2 border">Actions</th>
              </tr>
            </thead>
            <tbody>
              {submissions.map((sub) => (
                <tr key={sub.id} className="hover:bg-gray-50">
                  <td className="p-2 border">{sub.id}</td>
                  <td className="p-2 border">{sub.name}</td>
                  <td className="p-2 border">{sub.email}</td>
                  <td className="p-2 border">{sub.phone}</td>
                  <td className="p-2 border">
                    {sub.resume ? (
                      <a
                        href={sub.resume}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-blue-600 underline"
                      >
                        View Resume
                      </a>
                    ) : (
                      'N/A'
                    )}
                  </td>
                  <td className="p-2 border flex space-x-2">
                    <a
                      href={sub.resume || '#'}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="bg-green-600 text-white px-3 py-1 rounded-md"
                    >
                      View
                    </a>
                    <button
                      onClick={() => handleDelete(sub.id)}
                      className="bg-red-600 text-white px-3 py-1 rounded-md"
                    >
                      Delete
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

export default AdminHR;
