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

function Salary() {
  const [salaries, setSalaries] = useState([]);
  const [employees, setEmployees] = useState([]);
  const [employee, setEmployee] = useState('');
  const [grossSalary, setGrossSalary] = useState('');
  const [totalDeduction, setTotalDeduction] = useState('');
  const [monthOfPayment, setMonthOfPayment] = useState('');
  const [editId, setEditId] = useState(null);
  const [message, setMessage] = useState('');

  const headers = { Authorization: `Bearer ${localStorage.getItem('token')}` };

  const netSalary = useMemo(() => {
    return (Number(grossSalary) || 0) - (Number(totalDeduction) || 0);
  }, [grossSalary, totalDeduction]);

  const clearForm = () => {
    setEmployee('');
    setGrossSalary('');
    setTotalDeduction('');
    setMonthOfPayment('');
    setEditId(null);
  };

  const getSalaries = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/salaries/list', { headers });
      setSalaries(res.data);
    } catch (err) {
      console.error(err);
    }
  };

  const getEmployees = async () => {
    try {
      const res = await axios.get('http://localhost:5001/api/employees/list', { headers });
      setEmployees(res.data);
    } catch (err) {
      console.error(err);
    }
  };

  useEffect(() => {
    getEmployees();
    getSalaries();
  }, []);

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editId) {
        await axios.put(
          `http://localhost:5001/api/salaries/update/${editId}`,
          { employee, grossSalary, totalDeduction, monthOfPayment },
          { headers }
        );
        setMessage('Salary updated successfully');
      } else {
        await axios.post(
          'http://localhost:5001/api/salaries/add',
          { employee, grossSalary, totalDeduction, monthOfPayment },
          { headers }
        );
        setMessage('Salary added successfully');
      }
      clearForm();
      getSalaries();
    } catch (err) {
      setMessage(err.response?.data?.message || 'Failed to save salary');
    }
  };

  const handleDelete = async (id) => {
    if (!window.confirm('Delete this record?')) return;
    try {
      await axios.delete(`http://localhost:5001/api/salaries/delete/${id}`, { headers });
      getSalaries();
    } catch (err) {
      console.error(err);
    }
  };

  const handleEdit = (salary) => {
    setEditId(salary._id);
    setEmployee(salary.employee?._id || '');
    setGrossSalary(salary.grossSalary);
    setTotalDeduction(salary.totalDeduction);
    setMonthOfPayment(salary.monthOfPayment);
  };

  const isSuccess = message.includes('successfully');

  return (
    <div>
      <h1 className="mb-6 text-2xl font-bold">Salary Management</h1>

      {message && (
        <p className={isSuccess ? 'alert-success' : 'alert-error'}>{message}</p>
      )}

      <form onSubmit={handleSubmit} className="mb-6 box space-y-4">
        <h2 className="font-semibold">{editId ? 'Edit Salary' : 'Add Salary'}</h2>
        <div className="grid gap-4 sm:grid-cols-2">
          <div>
            <label className="mb-1 block text-sm">Employee</label>
            <select value={employee} onChange={(e) => setEmployee(e.target.value)} className="input-field" required>
              <option value="">Select employee</option>
              {employees.map((emp) => (
                <option key={emp._id} value={emp._id}>
                  {emp.firstName} {emp.lastName} ({emp.employeeNumber})
                </option>
              ))}
            </select>
          </div>
          <div>
            <label className="mb-1 block text-sm">Month</label>
            <input type="month" value={monthOfPayment} onChange={(e) => setMonthOfPayment(e.target.value)} className="input-field" required />
          </div>
          <div>
            <label className="mb-1 block text-sm">Gross Salary</label>
            <input type="number" value={grossSalary} onChange={(e) => setGrossSalary(e.target.value)} className="input-field" required />
          </div>
          <div>
            <label className="mb-1 block text-sm">Total Deduction</label>
            <input type="number" value={totalDeduction} onChange={(e) => setTotalDeduction(e.target.value)} className="input-field" required />
          </div>
        </div>
        <p className="text-sm">Net Salary: <strong>{netSalary}</strong></p>
        <div className="flex gap-2">
          <button type="submit" className="btn-primary">{editId ? 'Update' : 'Add Salary'}</button>
          {editId && (
            <button type="button" onClick={clearForm} className="btn-secondary">Cancel</button>
          )}
        </div>
      </form>

      <div className="box">
        <h2 className="mb-3 font-semibold">Salary List ({salaries.length})</h2>
        {salaries.length === 0 ? (
          <p className="text-gray-600">No salary records yet.</p>
        ) : (
          <div className="overflow-x-auto">
            <table className="data-table">
              <thead>
                <tr>
                  <th>Employee</th>
                  <th>Month</th>
                  <th>Gross</th>
                  <th>Deduction</th>
                  <th>Net</th>
                  <th>Actions</th>
                </tr>
              </thead>
              <tbody>
                {salaries.map((salary) => (
                  <tr key={salary._id}>
                    <td>{salary.employee?.firstName} {salary.employee?.lastName}</td>
                    <td>{salary.monthOfPayment}</td>
                    <td>{salary.grossSalary}</td>
                    <td>{salary.totalDeduction}</td>
                    <td>{salary.netSalary}</td>
                    <td>
                      <button type="button" onClick={() => handleEdit(salary)} className="btn-link mr-2">Edit</button>
                      <button type="button" onClick={() => handleDelete(salary._id)} className="btn-danger">Delete</button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

export default Salary;
