import { useEffect, useState } from "react";
import { getDepartments } from "../api/departmentApi";
import { createEmployee, deleteEmployee, getEmployees, updateEmployee } from "../api/employeeApi";


function EmployeePage() {
  const [departments, setDepartments] = useState([]);
  const [employees, setEmployees] = useState([]);
  const [message, setMessage] = useState("");
  const [editingId, setEditingId] = useState("");

  const [form, setForm] = useState({
    employeeNumber: "",
    firstName: "",
    lastName: "",
    position: "",
    address: "",
    telephone: "",
    gender: "Male",
    hiredDate: "",
    departmentId: "",
  });

  const loadData = async () => {
    const [deptRes, empRes] = await Promise.all([getDepartments(), getEmployees()]);
    setDepartments(deptRes.data);
    setEmployees(empRes.data);
  };

  useEffect(() => {
    let isMounted = true;

    const run = async () => {
      try {
        await loadData();
      } catch {
        if (isMounted) setMessage("Failed to load employees");
      }
    };

    run();
    return () => {
      isMounted = false;
    };
  }, []);


  const onChange = (event) => {
    setForm((prev) => ({ ...prev, [event.target.name]: event.target.value }));
  };

  const resetForm = () => {
    setForm({
      employeeNumber: "",
      firstName: "",
      lastName: "",
      position: "",
      address: "",
      telephone: "",
      gender: "Male",
      hiredDate: "",
      departmentId: "",
    });
    setEditingId("");
  };

  const onSubmit = async (event) => {
    event.preventDefault();
    setMessage("");
    const firstName = form.firstName.trim();
    const lastName = form.lastName.trim();
    const telephone = form.telephone.trim();
    const hiredDate = new Date(form.hiredDate);
    if (!/^[A-Za-z ]{2,50}$/.test(firstName) || !/^[A-Za-z ]{2,50}$/.test(lastName)) {
      setMessage("First name and last name should contain only letters (2-50 chars)");
      return;
    }
    if (!/^[0-9+\- ]{7,20}$/.test(telephone)) {
      setMessage("Telephone should contain valid digits (7-20 chars)");
      return;
    }
    if (Number.isNaN(hiredDate.getTime()) || hiredDate > new Date()) {
      setMessage("Hired date cannot be in the future");
      return;
    }
    try {
      const payload = {
        ...form,
        firstName,
        lastName,
        telephone,
      };

      if (editingId) {
        await updateEmployee(editingId, payload);
        setMessage("Employee updated");
      } else {
        await createEmployee(payload);
        setMessage("Employee saved");
      }

      resetForm();
      await loadData();

    } catch (error) {
      setMessage(error.response?.data?.message || "Failed to save employee");
    }
  };

  const onEdit = (item) => {
    setEditingId(item._id);
    setForm({
      employeeNumber: item.employeeNumber,
      firstName: item.firstName,
      lastName: item.lastName,
      position: item.position,
      address: item.address,
      telephone: item.telephone,
      gender: item.gender,
      hiredDate: item.hiredDate ? new Date(item.hiredDate).toISOString().split("T")[0] : "",
      departmentId: item.department?._id || item.departmentId || "",
    });
  };

  const onDelete = async (id) => {
    setMessage("");
    try {
      await deleteEmployee(id);
      setMessage("Employee deleted");
      await loadData();
      if (editingId === id) resetForm();
    } catch (error) {
      setMessage(error.response?.data?.message || "Failed to delete employee");
    }
  };

  return (
    <div className="space-y-4">
      <div className="ui-card p-5">
        <div className="rounded-xl bg-gradient-to-r from-blue-600 via-blue-600 to-indigo-700 p-4">
          <div className="flex items-start justify-between">
            <div>
              <h1 className="text-2xl font-bold text-white">Employee Management</h1>
              <p className="mt-1 text-sm text-blue-50">Manage and track all employees</p>
            </div>
            <div className="rounded-lg bg-white/20 px-4 py-2 backdrop-blur-sm">
              <div className="text-2xl font-bold text-white">{employees.length}</div>
              <div className="text-xs text-blue-100">Total Employees</div>
            </div>
          </div>
        </div>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        <section className="ui-card p-5">
          <h2 className="mb-4 text-lg font-semibold text-blue-900">{editingId ? '✏️ Edit Employee' : '➕ Add New Employee'}</h2>

        <form onSubmit={onSubmit} className="grid gap-3 md:grid-cols-2">
          <input
            name="employeeNumber"
            className="ui-input"
            placeholder="Employee Number"
            value={form.employeeNumber}
            onChange={onChange}
            minLength={2}
            required
          />

          <input
            name="firstName"
            className="ui-input"
            placeholder="First Name"
            value={form.firstName}
            onChange={onChange}
            pattern="[A-Za-z ]{2,50}"
            title="Use only letters (2-50 characters)"
            required
          />

          <input
            name="lastName"
            className="ui-input"
            placeholder="Last Name"
            value={form.lastName}
            onChange={onChange}
            pattern="[A-Za-z ]{2,50}"
            title="Use only letters (2-50 characters)"
            required
          />

          <input
            name="position"
            className="ui-input"
            placeholder="Position"
            value={form.position}
            onChange={onChange}
            minLength={2}
            required
          />

          <input
            name="address"
            className="ui-input md:col-span-2"
            placeholder="Address"
            value={form.address}
            onChange={onChange}
            minLength={3}
            required
          />

          <input
            name="telephone"
            className="ui-input"
            placeholder="Telephone"
            value={form.telephone}
            onChange={onChange}
            pattern="[0-9+\- ]{7,20}"
            title="Use 7-20 digits (plus and dash allowed)"
            required
          />

          <select
            name="gender"
            className="ui-select"
            value={form.gender}
            onChange={onChange}
          >
            <option>Male</option>
            <option>Female</option>
            <option>Other</option>
          </select>

          <input
            type="date"
            name="hiredDate"
            className="ui-input"
            value={form.hiredDate}
            onChange={onChange}
            max={new Date().toISOString().split("T")[0]}
            required
          />

          <select
            name="departmentId"
            className="ui-select"
            value={form.departmentId}
            onChange={onChange}
            required
          >
            <option value="">Select department</option>
            {departments.map((dept) => (
              <option key={dept._id} value={dept._id}>
                {dept.departmentCode} - {dept.departmentName}
              </option>
            ))}
          </select>

          <div className="flex gap-2 md:col-span-2">
            <button className="ui-btn ui-btn-primary flex-1">
              {editingId ? 'Update Employee' : 'Save Employee'}
            </button>
            {editingId && (
              <button
                type="button"
                className="ui-btn ui-btn-secondary"
                onClick={resetForm}
              >
                Cancel
              </button>
            )}
          </div>
        </form>

        {message && (
          <div className={`mt-3 rounded-lg p-3 text-sm ${
            message.includes('deleted') || message.includes('saved') || message.includes('updated')
              ? 'bg-green-50 text-green-700 ring-1 ring-green-200'
              : 'bg-red-50 text-red-700 ring-1 ring-red-200'
          }`}>
            {message}
          </div>
        )}
        </section>

        <section className="ui-card p-5">
          <h2 className="mb-4 text-lg font-semibold text-blue-900">👥 All Employees</h2>

        <div className="ui-table-wrap">
          <table className="ui-table">
            <thead>
              <tr>
                <th>Number</th>
                <th>Name</th>
                <th>Position</th>
                <th>Department</th>
                <th style={{ textAlign: "left" }}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {employees.map((item) => (
                <tr key={item._id}>
                  <td>{item.employeeNumber}</td>
                  <td>
                    {item.firstName} {item.lastName}
                  </td>
                  <td>{item.position}</td>
                  <td>{item.department?.departmentName}</td>
                  <td>
                    <div className="flex gap-2">
                      <button
                        type="button"
                        className="ui-btn ui-btn-amber"
                        onClick={() => onEdit(item)}
                      >
                        Edit
                      </button>
                      <button
                        type="button"
                        className="ui-btn ui-btn-danger"
                        onClick={() => onDelete(item._id)}
                      >
                        Delete
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    </div>

    </div>
  );
}

export default EmployeePage;
