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

const Salary = () => {
  const [salaries, setSalaries] = useState([]);
  const [employees, setEmployees] = useState([]);
  const [formData, setFormData] = useState({ 
    SalaryID: '', employeeNumber: '', GlossSalary: '', TotalDeduction: '', NetSalary: '', month: '' 
  });
  const [isEditing, setIsEditing] = useState(false);

  useEffect(() => {
    fetchSalaries();
    fetchEmployees();
  }, []);

  useEffect(() => {
    const gross = parseFloat(formData.GlossSalary) || 0;
    const deduction = parseFloat(formData.TotalDeduction) || 0;
    setFormData(prev => ({ ...prev, NetSalary: (gross - deduction).toString() }));
  }, [formData.GlossSalary, formData.TotalDeduction]);

  const fetchSalaries = async () => {
    const res = await axios.get('http://localhost:5000/api/salary');
    setSalaries(res.data);
  };

  const fetchEmployees = async () => {
    const res = await axios.get('http://localhost:5000/api/employee');
    setEmployees(res.data);
  };

  const handleSave = async () => {
    // 1. Validation: Net Salary ntigomba kuba negative
    const gross = parseFloat(formData.GlossSalary);
    const deduction = parseFloat(formData.TotalDeduction);
    
    if (deduction > gross) {
        alert("Ikosa: Total Deduction ntigomba kurenga Gross Salary!");
        return; 
    }

    try {
        if (isEditing) {
            await axios.put(`http://localhost:5000/api/salary/${formData.SalaryID}`, formData);
        } else {
            await axios.post('http://localhost:5000/api/salary', formData);
        }
        fetchSalaries();
        resetForm();
    } catch (err) { alert('Error: ' + err.message); }
};
  const handleDelete = async (SalaryID) => {
    if (window.confirm("Are you sure?")) {
      await axios.delete(`http://localhost:5000/api/salary/${SalaryID}`);
      fetchSalaries();
    }
  };

  const handleEdit = (s) => {
    setFormData(s);
    setIsEditing(true);
  };

  const resetForm = () => {
    setFormData({ SalaryID: '', employeeNumber: '', GlossSalary: '', TotalDeduction: '', NetSalary: '', month: '' });
    setIsEditing(false);
  };

  return (
    <div className="p-6 max-w-5xl mx-auto">
      <h2 className="text-2xl font-bold mb-6">Salary Management</h2>
      <div className="bg-white p-6 rounded-lg shadow-md border mb-8">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <select value={formData.employeeNumber} onChange={e => setFormData({...formData, employeeNumber: e.target.value})} className="border p-2 rounded">
            <option value="">Select Employee</option>
            {employees.map(emp => <option key={emp.employeeNumber} value={emp.employeeNumber}>{emp.FirstName}</option>)}
          </select>
          <input type="number" placeholder="Gross Salary" value={formData.GlossSalary} onChange={e => setFormData({...formData, GlossSalary: e.target.value})} className="border p-2 rounded"/>
          <input type="number" placeholder="Total Deduction" value={formData.TotalDeduction} onChange={e => setFormData({...formData, TotalDeduction: e.target.value})} className="border p-2 rounded"/>
          <input type="text" placeholder="Net Salary" value={formData.NetSalary} readOnly className="border p-2 rounded bg-gray-100 font-bold"/>
          <input type="month" value={formData.month} onChange={e => setFormData({...formData, month: e.target.value})} className="border p-2 rounded"/>
        </div>
        <div className="mt-4 flex gap-2">
          <button onClick={handleSave} className="bg-blue-600 text-white px-6 py-2 rounded">{isEditing ? 'Update' : 'Add'}</button>
          {isEditing && <button onClick={resetForm} className="bg-gray-400 text-white px-6 py-2 rounded">Cancel</button>}
        </div>
      </div>
      <div className="overflow-x-auto">
        <table className="w-full bg-white border">
          <thead className="bg-gray-200">
            <tr><th>Emp #</th><th>Gross</th><th>Deduction</th><th>Net Salary</th><th>Month</th><th>Actions</th></tr>
          </thead>
          <tbody>
            {salaries.map((s, i) => (
              <tr key={i} className="border-b text-center">
                <td>{s.employeeNumber}</td><td>{s.GlossSalary}</td><td>{s.TotalDeduction}</td><td>{s.NetSalary}</td><td>{s.month}</td>
                <td className="p-2">
                  <button onClick={() => handleEdit(s)} className="text-blue-600 mr-2">Edit</button>
                  <button onClick={() => handleDelete(s.SalaryID)} className="text-red-600">Delete</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};
export default Salary;