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

const EmployeeForm = () => {
  const [formData, setFormData] = useState({
    fname: '', lname: '', position: '', address: '',
    telephone: '', gender: 'Male', hireDate: '', deptCode: '', salaryID: ''
  });
  const [departments, setDepartments] = useState([]);
  const [salaries, setSalaries] = useState([]);
  const [employees, setEmployees] = useState([]);
  const [message, setMessage] = useState('');
  const [showForm, setShowForm] = useState(true);
  const [loading, setLoading] = useState(false);

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

  const fetchData = async () => {
    setLoading(true);
    try {
      console.log('Fetching departments and salaries...');
      
      const [deptRes, salRes, empRes] = await Promise.all([
        axios.get('http://localhost:5000/api/departments', { withCredentials: true }),
        axios.get('http://localhost:5000/api/salaries', { withCredentials: true }),
        axios.get('http://localhost:5000/api/employees', { withCredentials: true })
      ]);
      
      console.log('Departments received:', deptRes.data);
      console.log('Salaries received:', salRes.data);
      console.log('Employees received:', empRes.data);
      
      setDepartments(deptRes.data);
      setSalaries(salRes.data);
      setEmployees(empRes.data);
      
      if (deptRes.data.length === 0) {
        setMessage({ type: 'warning', text: 'No departments found. Please add departments first!' });
      }
    } catch (error) {
      console.error('Error fetching data:', error);
      setMessage({ type: 'error', text: 'Failed to load data: ' + (error.response?.data?.message || error.message) });
    } finally {
      setLoading(false);
    }
  };

  const handleChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setMessage('');

    // Validate required fields
    if (!formData.fname || !formData.lname || !formData.position || !formData.telephone || 
        !formData.gender || !formData.hireDate || !formData.deptCode || !formData.salaryID) {
      setMessage({ type: 'error', text: 'All required fields must be filled!' });
      setLoading(false);
      return;
    }

    try {
      console.log('Sending employee data:', formData);
      
      const response = await axios.post('http://localhost:5000/api/employees', formData, { 
        withCredentials: true,
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      console.log('Response:', response.data);
      
      setMessage({ type: 'success', text: 'Employee added successfully!' });
      setFormData({ 
        fname: '', lname: '', position: '', address: '',
        telephone: '', gender: 'Male', hireDate: '', deptCode: '', salaryID: '' 
      });
      fetchData(); // Refresh the list
      setTimeout(() => setMessage(''), 3000);
    } catch (error) {
      console.error('Error adding employee:', error);
      let errorMessage = 'Failed to add employee';
      if (error.response) {
        errorMessage = error.response.data?.message || error.response.data?.error || errorMessage;
      } else if (error.request) {
        errorMessage = 'No response from server. Check if backend is running.';
      } else {
        errorMessage = error.message;
      }
      setMessage({ type: 'error', text: errorMessage });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <Navbar />
      <div className="p-6 bg-gray-100 min-h-screen">
        <div className="max-w-6xl mx-auto">
          <div className="flex justify-between items-center mb-6">
            <h1 className="text-3xl font-bold text-gray-800">Employee Management</h1>
            <button
              onClick={() => setShowForm(!showForm)}
              className="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700"
            >
              {showForm ? ' View Employees' : ' Add Employee'}
            </button>
          </div>

          {showForm ? (
            <div className="bg-white rounded-lg shadow-md p-6">
              <h2 className="text-xl font-bold mb-4">Add New Employee</h2>
              
              {message && (
                <div className={`p-3 rounded mb-4 ${message.type === 'success' ? 'bg-green-100 text-green-700' : message.type === 'warning' ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700'}`}>
                  {message.type === 'success' ? ' ' : message.type === 'warning' ? ' yes' : ' no'}{message.text}
                </div>
              )}

              <form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium mb-1">First Name *</label>
                  <input 
                    type="text" 
                    name="fname" 
                    placeholder="First Name" 
                    value={formData.fname} 
                    onChange={handleChange} 
                    className="w-full border p-2 rounded focus:ring-2 focus:ring-blue-500"
                    required 
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">Last Name *</label>
                  <input 
                    type="text" 
                    name="lname" 
                    placeholder="Last Name" 
                    value={formData.lname} 
                    onChange={handleChange} 
                    className="w-full border p-2 rounded focus:ring-2 focus:ring-blue-500"
                    required 
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">Position *</label>
                  <input 
                    type="text" 
                    name="position" 
                    placeholder="Position" 
                    value={formData.position} 
                    onChange={handleChange} 
                    className="w-full border p-2 rounded focus:ring-2 focus:ring-blue-500"
                    required 
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">Address</label>
                  <input 
                    type="text" 
                    name="address" 
                    placeholder="Address" 
                    value={formData.address} 
                    onChange={handleChange} 
                    className="w-full border p-2 rounded"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">Telephone *</label>
                  <input 
                    type="tel" 
                    name="telephone" 
                    placeholder="Telephone" 
                    value={formData.telephone} 
                    onChange={handleChange} 
                    className="w-full border p-2 rounded focus:ring-2 focus:ring-blue-500"
                    required 
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">Gender *</label>
                  <select 
                    name="gender" 
                    value={formData.gender} 
                    onChange={handleChange} 
                    className="w-full border p-2 rounded focus:ring-2 focus:ring-blue-500"
                    required
                  >
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                  </select>
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">Hire Date *</label>
                  <input 
                    type="date" 
                    name="hireDate" 
                    value={formData.hireDate} 
                    onChange={handleChange} 
                    className="w-full border p-2 rounded focus:ring-2 focus:ring-blue-500"
                    required 
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">Department *</label>
                  <select 
                    name="deptCode" 
                    value={formData.deptCode} 
                    onChange={handleChange} 
                    className="w-full border p-2 rounded focus:ring-2 focus:ring-blue-500"
                    required
                  >
                    <option value="">Select Department</option>
                    {departments.length === 0 ? (
                      <option value="" disabled> No departments available. Please add departments first!</option>
                    ) : (
                      departments.map(dept => (
                        <option key={dept.deptCode} value={dept.deptCode}>
                          {dept.deptCode} - {dept.deptName}
                        </option>
                      ))
                    )}
                  </select>
                  {departments.length === 0 && (
                    <p className="text-xs text-red-500 mt-1">
                      No departments found! Please go to Department page and add departments first.
                    </p>
                  )}
                  {departments.length > 0 && (
                    <p className="text-xs text-green-500 mt-1">
                      ✓ {departments.length} department(s) available
                    </p>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">Salary Structure *</label>
                  <select 
                    name="salaryID" 
                    value={formData.salaryID} 
                    onChange={handleChange} 
                    className="w-full border p-2 rounded focus:ring-2 focus:ring-blue-500"
                    required
                  >
                    <option value="">Select Salary</option>
                    {salaries.length === 0 ? (
                      <option value="" disabled>No salary records available. Please add salary first!</option>
                    ) : (
                      salaries.map(sal => (
                        <option key={sal.salaryID} value={sal.salaryID}>
                          ID: {sal.salaryID} - {parseFloat(sal.netSalary).toLocaleString()} RWF/month
                        </option>
                      ))
                    )}
                  </select>
                  {salaries.length === 0 && (
                    <p className="text-xs text-red-500 mt-1">
                     No salary records found! Please go to Salary page and add salary records first.
                    </p>
                  )}
                </div>

                <div className="md:col-span-2">
                  <button 
                    type="submit" 
                    disabled={loading || departments.length === 0 || salaries.length === 0}
                    className="bg-green-600 text-white px-6 py-2 rounded-md hover:bg-green-700 disabled:bg-gray-400 disabled:cursor-not-allowed"
                  >
                    {loading ? 'Adding Employee...' : 'Add Employee'}
                  </button>
                </div>
              </form>
            </div>
          ) : (
            <div className="bg-white rounded-lg shadow-md p-6">
              <h2 className="text-xl font-bold mb-4">Employee List</h2>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="p-2 text-left">Name</th>
                      <th className="p-2 text-left">Position</th>
                      <th className="p-2 text-left">Department</th>
                      <th className="p-2 text-left">Phone</th>
                      <th className="p-2 text-left">Gender</th>
                    </tr>
                  </thead>
                  <tbody>
                    {employees.length === 0 ? (
                      <tr>
                        <td colSpan="5" className="p-4 text-center text-gray-500">No employees found. Add your first employee!</td>
                      </tr>
                    ) : (
                      employees.map(emp => (
                        <tr key={emp.empID} className="border-t">
                          <td className="p-2">{emp.fname} {emp.lname}</td>
                          <td className="p-2">{emp.position}</td>
                          <td className="p-2">{emp.deptName || emp.deptCode}</td>
                          <td className="p-2">{emp.telephone}</td>
                          <td className="p-2">{emp.gender}</td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default EmployeeForm;