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

const SalaryForm = () => {
  const [formData, setFormData] = useState({ grossSalary: '', totalDeduction: '', netSalary: '', month: '' });
  const [salaries, setSalaries] = useState([]);
  const [editingId, setEditingId] = useState(null);
  const [message, setMessage] = useState('');

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

  const fetchSalaries = async () => {
    try {
      const res = await axios.get('http://localhost:5000/api/salaries', { withCredentials: true });
      setSalaries(res.data);
    } catch (error) {
      console.error('Error fetching salaries:', error);
    }
  };

  const calculateNetSalary = (gross, deduction) => {
    return parseFloat(gross) - parseFloat(deduction);
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
    
    if (name === 'grossSalary' || name === 'totalDeduction') {
      const gross = name === 'grossSalary' ? value : formData.grossSalary;
      const deduction = name === 'totalDeduction' ? value : formData.totalDeduction;
      if (gross && deduction) {
        setFormData(prev => ({ ...prev, netSalary: calculateNetSalary(gross, deduction) }));
      }
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editingId) {
        await axios.put(`http://localhost:5000/api/salaries/${editingId}`, formData, { withCredentials: true });
        setMessage({ type: 'success', text: 'Salary updated successfully!' });
        setEditingId(null);
      } else {
        await axios.post('http://localhost:5000/api/salaries', formData, { withCredentials: true });
        setMessage({ type: 'success', text: 'Salary added successfully!' });
      }
      setFormData({ grossSalary: '', totalDeduction: '', netSalary: '', month: '' });
      fetchSalaries();
      setTimeout(() => setMessage(''), 3000);
    } catch (error) {
      setMessage({ type: 'error', text: 'Operation failed' });
    }
  };

  const handleEdit = (salary) => {
    setEditingId(salary.salaryID);
    setFormData({
      grossSalary: salary.grossSalary,
      totalDeduction: salary.totalDeduction,
      netSalary: salary.netSalary,
      month: salary.month
    });
  };

  const handleDelete = async (id) => {
    if (window.confirm('Are you sure you want to delete this salary record?')) {
      try {
        await axios.delete(`http://localhost:5000/api/salaries/${id}`, { withCredentials: true });
        setMessage({ type: 'success', text: 'Salary deleted successfully!' });
        fetchSalaries();
        setTimeout(() => setMessage(''), 3000);
      } catch (error) {
        setMessage({ type: 'error', text: 'Cannot delete - salary is linked to department/employee' });
      }
    }
  };

  const handleCancelEdit = () => {
    setEditingId(null);
    setFormData({ grossSalary: '', totalDeduction: '', netSalary: '', month: '' });
  };

  return (
    <div>
      <Navbar />
      <div className="p-6 bg-gray-100 min-h-screen">
        <div className="max-w-6xl mx-auto">
          <h1 className="text-3xl font-bold text-gray-800 mb-6">Salary Management</h1>

          <div className="bg-white rounded-lg shadow-md p-6 mb-8">
            <h2 className="text-xl font-bold mb-4">{editingId ? 'Edit Salary' : 'Add New Salary'}</h2>
            <form onSubmit={handleSubmit} className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <input type="number" name="grossSalary" placeholder="Gross Salary (RWF)" value={formData.grossSalary} onChange={handleChange} className="border p-2 rounded" required />
              <input type="number" name="totalDeduction" placeholder="Total Deduction (RWF)" value={formData.totalDeduction} onChange={handleChange} className="border p-2 rounded" required />
              <input type="number" name="netSalary" placeholder="Net Salary (auto-calculated)" value={formData.netSalary} className="border p-2 rounded bg-gray-100" readOnly />
              <input type="number" name="month" placeholder="Month (1-12)" value={formData.month} onChange={handleChange} className="border p-2 rounded" required />
              <div className="md:col-span-2 flex space-x-2">
                {message && <div className={`p-2 rounded mb-2 flex-1 ${message.type === 'success' ? 'bg-green-100 text-green-700' : 'bg-red-100 text-red-700'}`}>{message.text}</div>}
              </div>
              <div className="md:col-span-2 flex space-x-2">
                <button type="submit" className="bg-green-600 text-white px-6 py-2 rounded-md hover:bg-green-700">{editingId ? 'Update Salary' : 'Add Salary'}</button>
                {editingId && <button type="button" onClick={handleCancelEdit} className="bg-gray-500 text-white px-6 py-2 rounded-md hover:bg-gray-600">Cancel</button>}
              </div>
            </form>
          </div>

          <div className="bg-white rounded-lg shadow-md p-6">
            <h2 className="text-xl font-bold mb-4">Salary Records</h2>
            <div className="overflow-x-auto">
              <table className="w-full">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="p-2">ID</th><th>Gross Salary</th><th>Deduction</th><th>Net Salary</th><th>Month</th><th>Actions</th>
                  </tr>
                </thead>
                <tbody>
                  {salaries.map(sal => (
                    <tr key={sal.salaryID} className="border-t">
                      <td className="p-2">{sal.salaryID}</td>
                      <td className="p-2">{sal.grossSalary?.toLocaleString()} RWF</td>
                      <td className="p-2">{sal.totalDeduction?.toLocaleString()} RWF</td>
                      <td className="p-2 text-green-600 font-bold">{sal.netSalary?.toLocaleString()} RWF</td>
                      <td className="p-2">{sal.month}</td>
                      <td className="p-2">
                        <button onClick={() => handleEdit(sal)} className="bg-yellow-500 text-white px-2 py-1 rounded mr-2 text-sm">Edit</button>
                        <button onClick={() => handleDelete(sal.salaryID)} className="bg-red-500 text-white px-2 py-1 rounded text-sm">Delete</button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default SalaryForm;