import React, { useEffect, useState } from "react";
import { createEmployee, getEmployees, updateEmployee, deleteEmployee } from "../api/employeeApi";
import Layout from "../components/Layout";
import Message from "../components/Message";

const initialForm = {
  employeeCode: "",
  firstName: "",
  lastName: "",
  department: "",
  position: "",
  baseSalary: "",
  hireDate: "",
  email: "",
  phone: ""
};

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

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

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

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

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

    if (!formData.employeeCode || !formData.firstName || !formData.lastName || !formData.department || !formData.position || !formData.baseSalary || !formData.hireDate) {
      setMessageType("error");
      setMessage("All required fields must be filled");
      return;
    }

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

  const handleEdit = (employee) => {
    setEditingId(employee._id);
    setFormData({
      employeeCode: employee.employeeCode,
      firstName: employee.firstName,
      lastName: employee.lastName,
      department: employee.department,
      position: employee.position,
      baseSalary: employee.baseSalary,
      hireDate: employee.hireDate?.slice(0, 10),
      email: employee.email || "",
      phone: employee.phone || ""
    });
  };

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

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

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

  return (
    <Layout title="Employees" 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">
          <input name="employeeCode" placeholder="Employee Code *" value={formData.employeeCode} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="firstName" placeholder="First Name *" value={formData.firstName} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="lastName" placeholder="Last Name *" value={formData.lastName} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="department" placeholder="Department *" value={formData.department} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="position" placeholder="Position *" value={formData.position} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="baseSalary" type="number" min="0" placeholder="Base Salary *" value={formData.baseSalary} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="hireDate" type="date" value={formData.hireDate} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="email" placeholder="Email" value={formData.email} onChange={handleChange} className="rounded-md border border-primary bg-secondary p-3 outline-none" />
          <input name="phone" placeholder="Phone" value={formData.phone} onChange={handleChange} className="rounded-md border border-primary bg-secondary 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 Employee" : "Save Employee"}
          </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-[800px] border border-primary text-left text-sm">
          <thead className="bg-primary text-secondary">
            <tr>
              <th className="p-3">Code</th>
              <th className="p-3">Name</th>
              <th className="p-3">Department</th>
              <th className="p-3">Position</th>
              <th className="p-3">Base Salary</th>
              <th className="p-3">Actions</th>
            </tr>
          </thead>
          <tbody>
            {employees.length === 0 ? (
              <tr className="border-t border-primary">
                <td colSpan="6" className="p-3 text-center">No employees recorded</td>
              </tr>
            ) : (
              employees.map((employee) => (
                <tr key={employee._id} className="border-t border-primary">
                  <td className="p-3">{employee.employeeCode}</td>
                  <td className="p-3">{employee.firstName} {employee.lastName}</td>
                  <td className="p-3">{employee.department}</td>
                  <td className="p-3">{employee.position}</td>
                  <td className="p-3">{Number(employee.baseSalary).toLocaleString()} FRW</td>
                  <td className="p-3">
                    <button onClick={() => handleEdit(employee)} className="mr-2 font-semibold text-primary">Edit</button>
                    <button onClick={() => handleDelete(employee._id)} className="font-semibold text-red-600">Delete</button>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </Layout>
  );
};

export default EmployeePage;
