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

const DepartmentForm = () => {
  const [formData, setFormData] = useState({ 
    deptCode: '', 
    deptName: '', 
    salaryID: '' 
  });
  const [departments, setDepartments] = useState([]);
  const [salaries, setSalaries] = useState([]);
  const [message, setMessage] = useState('');
  const [showForm, setShowForm] = useState(true);
  const [loading, setLoading] = useState(false);

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

  const fetchData = async () => {
    try {
      console.log('Fetching departments and salaries...');
      const [deptRes, salRes] = await Promise.all([
        axios.get('http://localhost:5000/api/departments', { withCredentials: true }),
        axios.get('http://localhost:5000/api/salaries', { withCredentials: true })
      ]);
      console.log('Departments:', deptRes.data);
      console.log('Salaries:', salRes.data);
      setDepartments(deptRes.data);
      setSalaries(salRes.data);
    } catch (error) {
      console.error('Error fetching data:', error);
      setMessage({ type: 'error', text: 'Failed to load data: ' + (error.response?.data?.message || error.message) });
    }
  };

  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.deptCode || !formData.deptName || !formData.salaryID) {
      setMessage({ type: 'error', text: 'All fields are required: Department Code, Name, and Salary ID' });
      setLoading(false);
      return;
    }

    try {
      console.log('Sending department data:', formData);
      
      const response = await axios.post('http://localhost:5000/api/departments', formData, { 
        withCredentials: true,
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      console.log('Response:', response.data);
      
      setMessage({ type: 'success', text: 'Department added successfully!' });
      setFormData({ deptCode: '', deptName: '', salaryID: '' });
      fetchData(); // Refresh the list
      setTimeout(() => setMessage(''), 3000);
    } catch (error) {
      console.error('Error adding department:', error);
      console.error('Error response:', error.response);
      
      let errorMessage = 'Failed to add department';
      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">Department</h1>
            <button 
              onClick={() => setShowForm(!showForm)} 
              className="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700"
            >
              {showForm ? ' View Departments' : ' Add Department'}
            </button>
          </div>

          {showForm ? (
            <div className="bg-white rounded-lg shadow-md p-6">
              <h2 className="text-xl font-bold mb-4">Add New Department</h2>
              <form onSubmit={handleSubmit} className="space-y-4">
                <div>
                  <label className="block text-sm font-medium mb-1">Department Code *</label>
                  <input 
                    type="text" 
                    name="deptCode" 
                    placeholder="e.g., HR, IT, SALES" 
                    value={formData.deptCode} 
                    onChange={handleChange} 
                    className="w-full border p-2 rounded focus:ring-2 focus:ring-blue-500"
                    required 
                  />
                  <p className="text-xs text-gray-500 mt-1">Unique code for the department (max 10 characters)</p>
                </div>

                <div>
                  <label className="block text-sm font-medium mb-1">Department Name *</label>
                  <input 
                    type="text" 
                    name="deptName" 
                    placeholder="Full department name" 
                    value={formData.deptName} 
                    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">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 Structure</option>
                    {salaries.length === 0 ? (
                      <option disabled>No salary records found. Please add salary first.</option>
                    ) : (
                      salaries.map(sal => (
                        <option key={sal.salaryID} value={sal.salaryID}>
                          ID: {sal.salaryID} - Gross: {parseFloat(sal.grossSalary).toLocaleString()} RWF - Net: {parseFloat(sal.netSalary).toLocaleString()} RWF
                        </option>
                      ))
                    )}
                  </select>
                  {salaries.length === 0 && (
                    <p className="text-xs text-red-500 mt-1">
                       No salary records available. Please add salary records first before creating departments.
                    </p>
                  )}
                </div>

                {message && (
                  <div className={`p-3 rounded ${message.type === 'success' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>
                    {message.type === 'success' ? ' ' : ' '}{message.text}
                  </div>
                )}

                <button 
                  type="submit" 
                  disabled={loading || 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...' : 'Add Department'}
                </button>
              </form>
            </div>
          ) : (
            <div className="bg-white rounded-lg shadow-md p-6">
              <h2 className="text-xl font-bold mb-4">Department List</h2>
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="p-2 text-left">Code</th>
                      <th className="p-2 text-left">Name</th>
                      <th className="p-2 text-left">Gross Salary</th>
                      <th className="p-2 text-left">Net Salary</th>
                      <th className="p-2 text-left">Month</th>
                    </tr>
                  </thead>
                  <tbody>
                    {departments.length === 0 ? (
                      <tr>
                        <td colSpan="5" className="p-4 text-center text-gray-500">No departments found. Add your first department!</td>
                      </tr>
                    ) : (
                      departments.map(dept => (
                        <tr key={dept.deptCode} className="border-t">
                          <td className="p-2 font-medium">{dept.deptCode}</td>
                          <td className="p-2">{dept.deptName}</td>
                          <td className="p-2">{dept.grossSalary ? parseFloat(dept.grossSalary).toLocaleString() : 'N/A'} RWF</td>
                          <td className="p-2 text-green-600 font-bold">{dept.netSalary ? parseFloat(dept.netSalary).toLocaleString() : 'N/A'} RWF</td>
                          <td className="p-2">{dept.month || 'N/A'}</td>
                        </tr>
                      ))
                    )}
                  </tbody>
                </table>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default DepartmentForm;