import React, { useEffect, useState } from "react";
import { createPayroll, getPayrolls, updatePayroll, deletePayroll } from "../api/payrollApi";
import { getEmployees } from "../api/employeeApi";
import Layout from "../components/Layout";
import Message from "../components/Message";

const initialForm = {
  employee: "",
  month: new Date().getMonth() + 1,
  year: new Date().getFullYear(),
  basicPay: "",
  allowances: "0",
  deductions: "0",
  netPay: ""
};

const PayrollPage = ({ user, setUser }) => {
  const [formData, setFormData] = useState(initialForm);
  const [payrolls, setPayrolls] = useState([]);
  const [employees, setEmployees] = useState([]);
  const [editingId, setEditingId] = useState(null);
  const [message, setMessage] = useState("");
  const [messageType, setMessageType] = useState("");

  const loadPayrolls = async () => {
    const data = await getPayrolls();
    setPayrolls(data);
  };

  const loadEmployees = async () => {
    const data = await getEmployees();
    setEmployees(data);
  };

  useEffect(() => {
    loadPayrolls();
    loadEmployees();
  }, []);

  useEffect(() => {
    const basic = parseFloat(formData.basicPay) || 0;
    const allowances = parseFloat(formData.allowances) || 0;
    const deductions = parseFloat(formData.deductions) || 0;
    setFormData((prev) => ({ ...prev, netPay: Math.max(0, basic + allowances - deductions) }));
  }, [formData.basicPay, formData.allowances, formData.deductions]);

  const handleChange = (event) => {
    setFormData({ ...formData, [event.target.name]: event.target.value });
  };

  const handleEmployeeSelect = (event) => {
    const empId = event.target.value;
    const selected = employees.find((e) => e._id === empId);
    setFormData({
      ...formData,
      employee: empId,
      basicPay: selected ? selected.baseSalary : ""
    });
  };

  const handleSubmit = async (event) => {
    event.preventDefault();

    if (!formData.employee || !formData.basicPay || formData.netPay === undefined) {
      setMessageType("error");
      setMessage("Employee, basic pay and net pay are required");
      return;
    }

    try {
      if (editingId) {
        const data = await updatePayroll(editingId, formData);
        setMessageType("success");
        setMessage(data.message);
        setEditingId(null);
      } else {
        const data = await createPayroll(formData);
        setMessageType("success");
        setMessage(data.message);
      }
      setFormData(initialForm);
      loadPayrolls();
    } catch (error) {
      setMessageType("error");
      setMessage(error.message);
    }
  };

  const handleEdit = (payroll) => {
    setEditingId(payroll._id);
    setFormData({
      employee: payroll.employee?._id || "",
      month: payroll.month,
      year: payroll.year,
      basicPay: payroll.basicPay,
      allowances: payroll.allowances,
      deductions: payroll.deductions,
      netPay: payroll.netPay
    });
  };

  const handleCancelEdit = () => {
    setEditingId(null);
    setFormData(initialForm);
  };

  const handleDelete = async (id) => {
    if (!window.confirm("Delete this payroll record?")) return;

    try {
      const data = await deletePayroll(id);
      setMessageType("success");
      setMessage(data.message);
      loadPayrolls();
    } catch (error) {
      setMessageType("error");
      setMessage(error.message);
    }
  };

  const monthNames = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

  return (
    <Layout title="Payroll" user={user} setUser={setUser}>
      <form onSubmit={handleSubmit} className="rounded-md border border-primary p-4">
        <Message message={message} type={messageType} />
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          <select name="employee" value={formData.employee} onChange={handleEmployeeSelect} className="rounded-md border border-primary bg-secondary p-3 outline-none">
            <option value="">Select Employee *</option>
            {employees.map((emp) => (
              <option key={emp._id} value={emp._id}>{emp.firstName} {emp.lastName} ({emp.employeeCode})</option>
            ))}
          </select>
          <select name="month" value={formData.month} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none">
            {monthNames.slice(1).map((name, idx) => (
              <option key={idx + 1} value={idx + 1}>{name}</option>
            ))}
          </select>
          <input name="year" type="number" min="2020" max="2030" placeholder="Year" value={formData.year} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="basicPay" type="number" min="0" placeholder="Basic Pay *" value={formData.basicPay} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="allowances" type="number" min="0" placeholder="Allowances" value={formData.allowances} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="deductions" type="number" min="0" placeholder="Deductions" value={formData.deductions} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="netPay" type="number" min="0" placeholder="Net Pay *" value={formData.netPay} readOnly className="rounded-md border border-primary bg-gray-100 p-3 outline-none" />
        </div>
        <div className="mt-4 flex gap-3">
          <button className="rounded-md bg-primary px-5 py-3 font-semibold text-secondary">
            {editingId ? "Update Payroll" : "Process Payroll"}
          </button>
          {editingId && (
            <button type="button" onClick={handleCancelEdit} className="rounded-md border border-primary px-5 py-3 font-semibold">
              Cancel
            </button>
          )}
        </div>
      </form>

      <div className="mt-6 overflow-x-auto">
        <table className="w-full min-w-[900px] border border-primary text-left text-sm">
          <thead className="bg-primary text-secondary">
            <tr>
              <th className="p-3">Employee</th>
              <th className="p-3">Period</th>
              <th className="p-3">Basic Pay</th>
              <th className="p-3">Allowances</th>
              <th className="p-3">Deductions</th>
              <th className="p-3">Net Pay</th>
              <th className="p-3">Actions</th>
            </tr>
          </thead>
          <tbody>
            {payrolls.length === 0 ? (
              <tr className="border-t border-primary">
                <td colSpan="7" className="p-3 text-center">No payroll records found</td>
              </tr>
            ) : (
              payrolls.map((payroll) => (
                <tr key={payroll._id} className="border-t border-primary">
                  <td className="p-3">{payroll.employee?.firstName} {payroll.employee?.lastName}</td>
                  <td className="p-3">{monthNames[payroll.month]} {payroll.year}</td>
                  <td className="p-3">{Number(payroll.basicPay).toLocaleString()} FRW</td>
                  <td className="p-3">{Number(payroll.allowances).toLocaleString()} FRW</td>
                  <td className="p-3">{Number(payroll.deductions).toLocaleString()} FRW</td>
                  <td className="p-3 font-bold">{Number(payroll.netPay).toLocaleString()} FRW</td>
                  <td className="p-3">
                    <button onClick={() => handleEdit(payroll)} className="mr-2 font-semibold text-primary">Edit</button>
                    <button onClick={() => handleDelete(payroll._id)} className="font-semibold text-red-600">Delete</button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </Layout>
  );
};

export default PayrollPage;
