import React, { useState, useEffect } from "react";
import { useSortableData } from "../../hooks/useSortableData";
import Avatar from "../common/Avatar";
const EmployeeList = ({ employees, onChange, bucket }) => {
  const [employeefiltered, setEmployeeFilter] = useState([]);
  const [employeeStatusList, setEmployeeStatusList] = useState([]);
  const [searchTerm, setSearchTerm] = useState("");
  useEffect(() => {
    setEmployeeFilter(employees?.filter((emp) => emp.email != null) || []);
  }, [employees]);

  // Initialize checked employees based on assignedEmployee prop
  useEffect(() => {
    if (Array.isArray(bucket?.employeeIds)) {
      const initialStatus = bucket?.employeeIds?.map((id) => ({
        employeeId: id,
        isActive: true,
      }));
      setEmployeeStatusList(initialStatus);
    }
  }, [bucket]);

  // Send updated list to parent
  useEffect(() => {
    if (onChange) {
      onChange(employeeStatusList);
    }
  }, [employeeStatusList]);

  const handleCheckboxChange = (id) => {
    setEmployeeStatusList((prev) => {
      const exists = prev.find((emp) => emp.employeeId === id);
      if (exists) {
        return prev.map((emp) =>
          emp.employeeId === id ? { ...emp, isActive: !emp.isActive } : emp
        );
      } else {
        return [...prev, { employeeId: id, isActive: true }];
      }
    });
  };

  const isChecked = (id) => {
    const found = employeeStatusList.find((emp) => emp.employeeId === id);
    return found?.isActive || false;
  };

  // Sorting
  const {
    items: sortedEmployees,
    requestSort,
    sortConfig,
  } = useSortableData(employeefiltered, {
    key: (e) => `${e?.firstName} ${e?.lastName}`,
    direction: "asc",
  });

  const getSortIcon = () => {
    if (!sortConfig) return null;
    return sortConfig.direction === "asc" ? (
      <i className="bx bx-caret-up text-secondary"></i>
    ) : (
      <i className="bx bx-caret-down text-secondary"></i>
    );
  };

  const filteredEmployees = sortedEmployees?.filter((employee) => {
    const fullName =
      `${employee?.firstName} ${employee?.lastName}`?.toLowerCase();
    return fullName.includes(searchTerm.toLowerCase());
  });
  return (
    <>
      <div className="d-flex justify-content-between align-items-center mt-2">
        <p className="m-0  fw-normal">Add Employee</p>
        <div className="px-1">
          <input
            type="search"
            className="form-control form-control-sm"
            placeholder="Search Employee..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
      </div>

      <div className="table-responsive px-1 my-1 px-sm-0">
        <table className="table align-middle mb-0">
          <thead className="table-light">
            <tr>
              <th
                onClick={() =>
                  requestSort((e) => `${e.firstName} ${e.lastName}`)
                }
                className="text-start cursor-pointer"
              >
                <span className="ps-2">Name {getSortIcon()}</span>
              </th>
              <th className="text-start">Role</th>
            </tr>
          </thead>

          <tbody>
            {employees.length === 0 ? (
              <tr>
                <td colSpan={4}>
                  <div className="d-flex justify-content-center align-items-center py-5">
                    No Employee Available
                  </div>
                </td>
              </tr>
            ) : filteredEmployees.length === 0 ? (
              <tr className="my-4">
                <td colSpan={4}>
                  <div className="d-flex justify-content-center align-items-center py-5">
                    No Matching Employee Found.
                  </div>
                </td>
              </tr>
            ) : (
              filteredEmployees?.map((employee) => (
                <tr key={employee.id}>
                  <td>
                    <div className="d-flex align-items-center text-start">
                      <input
                        className="form-check-input me-3 mt-1"
                        type="checkbox"
                        checked={isChecked(employee.id)}
                        onChange={() => handleCheckboxChange(employee?.id)}
                        disabled={bucket?.createdBy?.id === employee?.id}
                      />

                      <Avatar
                        size="xs"
                        classAvatar="m-0"
                        firstName={employee.firstName}
                        lastName={employee.lastName}
                      />
                      <span
                        className="text-truncate mx-0"
                        style={{ maxWidth: "150px" }}
                      >{`${employee.firstName} ${employee.lastName}`}</span>
                    </div>
                  </td>
                  <td className="text-start">
                    <small className="text-muted">{employee.jobRole}</small>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </>
  );
};

export default EmployeeList;
