import { useEffect, useState } from "react";
import axios from "axios";
import jsPDF from "jspdf";
import { Link } from "react-router-dom";

function Salary() {
  const [data, setData] = useState([]);
  const [employees, setEmployees] = useState([]);
  const [editingId, setEditingId] = useState("");
  const [form, setForm] = useState({
    employeeNumber: "",
    departmentCode: "",
    month: "",
    grossSalary: "",
    totalDeduction: ""
  });

  const emptyForm = {
    employeeNumber: "",
    departmentCode: "",
    month: "",
    grossSalary: "",
    totalDeduction: ""
  };

  const load = async () => {
    const [salaryRes, employeeRes] = await Promise.all([
      axios.get("http://localhost:5000/salary"),
      axios.get("http://localhost:5000/employees")
    ]);

    setData(salaryRes.data);
    setEmployees(employeeRes.data);
  };

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

  const save = async (e) => {
    e.preventDefault();

    const payload = {
      ...form,
      grossSalary: Number(form.grossSalary),
      totalDeduction: Number(form.totalDeduction)
    }

    if (editingId) {
      await axios.put(`http://localhost:5000/salary/${editingId}`, payload);
    } else {
      await axios.post("http://localhost:5000/salary", payload);
    }

    setForm(emptyForm);
    setEditingId("");
    load();
  };

  const pickEmployee = (employeeNumber) => {
    const selected = employees.find((item) => item.employeeNumber === employeeNumber);

    setForm({
      ...form,
      employeeNumber,
      departmentCode: selected?.departmentCode || ""
    });
  };

  const editSalary = (item) => {
    setEditingId(item._id);
    setForm({
      employeeNumber: item.employeeNumber,
      departmentCode: item.departmentCode,
      month: item.month,
      grossSalary: item.grossSalary,
      totalDeduction: item.totalDeduction
    });
  };

  const deleteSalary = async (id) => {
    try { 
      await axios.delete(`http://localhost:5000/salary/${id}`);

      if (editingId === id) {
        cancelEdit();
      }

      load();
      alert("Salary deleted");
    } catch (error) {
      alert("Delete failed. Please restart the server and try again.");
      console.log(error);
    }
  };

  const cancelEdit = () => {
    setEditingId("");
    setForm(emptyForm);
  };

  const pdf = () => {
    const doc = new jsPDF();
    doc.text("Payroll Report", 10, 10);

    data.forEach((s, i) => {
      doc.text(`${s.employeeNumber} - ${s.netSalary}`, 10, 20 + i * 10);
    });

    doc.save("report.pdf");
  };

  return (
    <div className="p">
      <div className="w">
        <div className="h c" style={{ background: "#0f172a", color: "white", border: "none" }}>
          <div>
            <p className="t" style={{ fontSize: 12, textTransform: "uppercase", letterSpacing: "0.3em", color: "#67e8f9" }}>Payroll</p>
            <h2 className="t" style={{ marginTop: 8, fontSize: 30, fontWeight: 700 }}>Salary Form</h2>
            <p className="m" style={{ marginTop: 8, color: "#cbd5e1" }}>Insert, retrieve, update, and delete are used here only.</p>
          </div>

          <div className="r">
            <Link to="/dashboard" className="b" style={{ background: "rgba(255,255,255,0.15)", color: "white" }}>
              Back
            </Link>
            <button
              type="button"
              onClick={pdf}
              className="b"
              style={{ background: "#22d3ee", color: "#0f172a" }}
            >
              Download PDF
            </button>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.05fr 0.95fr", gap: 24 }}>
          <form onSubmit={save} className="c">
            <h3 className="t" style={{ fontSize: 24, fontWeight: 700, color: "#0f172a" }}>
              {editingId ? "Update Salary" : "Add Salary"}
            </h3>
            <p className="m" style={{ marginTop: 8 }}>Retrieve, edit, and delete records from the list.</p>

            <div className="f" style={{ gridTemplateColumns: "repeat(2, 1fr)" }}>
              <div style={{ gridColumn: "1 / -1" }}>
                <label style={{ display: "block", marginBottom: 8, fontSize: 14, fontWeight: 600, color: "#334155" }}>Employee</label>
                <select
                  value={form.employeeNumber}
                  onChange={(e) => pickEmployee(e.target.value)}
                  className="i"
                  required
                >
                  <option value="">Select employee</option>
                  {employees.map((employee) => (
                    <option key={employee._id} value={employee.employeeNumber}>
                      {employee.employeeNumber} - {employee.firstName} {employee.lastName}
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label style={{ display: "block", marginBottom: 8, fontSize: 14, fontWeight: 600, color: "#334155" }}>Department Code</label>
                <input
                  value={form.departmentCode}
                  onChange={(e) => setForm({ ...form, departmentCode: e.target.value })}
                  placeholder="Department code"
                  className="i"
                  required
                />
              </div>

              <div>
                <label style={{ display: "block", marginBottom: 8, fontSize: 14, fontWeight: 600, color: "#334155" }}>Month</label>
                <input
                  value={form.month}
                  onChange={(e) => setForm({ ...form, month: e.target.value })}
                  placeholder="April 2026"
                  className="i"
                  required
                />
              </div>

              <div>
                <label style={{ display: "block", marginBottom: 8, fontSize: 14, fontWeight: 600, color: "#334155" }}>Gross Salary</label>
                <input
                  type="number"
                  value={form.grossSalary}
                  onChange={(e) => setForm({ ...form, grossSalary: e.target.value })}
                  placeholder="500000"
                  className="i"
                  required
                />
              </div>

              <div>
                <label style={{ display: "block", marginBottom: 8, fontSize: 14, fontWeight: 600, color: "#334155" }}>Total Deduction</label>
                <input
                  type="number"
                  value={form.totalDeduction}
                  onChange={(e) => setForm({ ...form, totalDeduction: e.target.value })}
                  placeholder="50000"
                  className="i"
                  required
                />
              </div>
            </div>

            <div className="r" style={{ marginTop: 24 }}>
              <button className="b" style={{ width: "100%", background: "#0f172a", color: "white" }}>
                {editingId ? "Update Salary" : "Save Salary"}
              </button>

              {editingId && (
                <button
                  type="button"
                  onClick={cancelEdit}
                  className="b"
                  style={{ width: "100%", background: "#e2e8f0", color: "#1e293b" }}
                >
                  Cancel
                </button>
              )}
            </div>
          </form>

          <div className="c">
            <div className="r" style={{ justifyContent: "space-between" }}>
              <div>
                <h3 className="t" style={{ fontSize: 24, fontWeight: 700, color: "#0f172a" }}>Saved Salaries</h3>
                <p className="m" style={{ marginTop: 8 }}>{data.length} record(s)</p>
              </div>
              <div className="b" style={{ background: "#dcfce7", color: "#15803d" }}>
                Retrieved list
              </div>
            </div>

            <div className="list">
              {data.length === 0 && (
                <div style={{ padding: 24, textAlign: "center", border: "1px dashed #cbd5e1", borderRadius: 20, color: "#64748b", background: "#f8fafc" }}>
                  No salary saved yet.
                </div>
              )}

              {data.map((s) => (
                <div key={s._id} className="c" style={{ padding: 16, boxShadow: "none" }}>
                  <div className="r" style={{ justifyContent: "space-between" }}>
                    <div>
                      <p className="text-lg font-bold text-slate-900">{s.employeeNumber}</p>
                      <p className="m" style={{ marginTop: 4 }}>{s.departmentCode} | {s.month}</p>
                      <p className="m" style={{ marginTop: 4 }}>
                        Gross: {s.grossSalary} | Deduction: {s.totalDeduction}
                      </p>
                    </div>

                    <div className="r">
                      <div className="b" style={{ background: "#dcfce7", color: "#15803d" }}>
                        Net: {s.netSalary}
                      </div>
                      <button
                        type="button"
                        onClick={() => editSalary(s)}
                        className="b"
                        style={{ background: "#fef3c7", color: "#b45309" }}
                      >
                        Edit
                      </button>
                      <button
                        type="button"
                        onClick={() => deleteSalary(s._id)}
                        className="b"
                        style={{ background: "#ffe4e6", color: "#be123c" }}
                      >
                        Delete
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Salary;
