import React, { useState, useEffect, useRef, useCallback } from "react";
import moment from "moment";
import showToast from "../../services/toastService";
import { Link, NavLink, useNavigate } from "react-router-dom";
import Avatar from "../../components/common/Avatar";
import Breadcrumb from "../../components/common/Breadcrumb";
import ManageEmp from "../../components/Employee/ManageRole";
import {
  useEmployeesAllOrByProjectId,
  useEmployeesByOrganization,
  useSuspendEmployee,
} from "../../hooks/useEmployees";
import { useProjectName, useProjects } from "../../hooks/useProjects";
import { useProfile } from "../../hooks/useProfile";

import {
  ITEMS_PER_PAGE,
  MANAGE_EMPLOYEES,
  VIEW_ALL_EMPLOYEES,
  VIEW_TEAM_MEMBERS,
} from "../../utils/constants";
import { clearCacheKey } from "../../slices/apiDataManager";
import SuspendEmp from "../../components/Employee/SuspendEmp"; // Keep if you use SuspendEmp
import {
  exportToCSV,
  exportToExcel,
  printTable,
  exportToPDF,
} from "../../utils/tableExportUtils";
import EmployeeRepository from "../../repositories/EmployeeRepository";
import ManageEmployee from "../../components/Employee/ManageEmployee";
import ConfirmModal from "../../components/common/ConfirmModal";
import { useDispatch, useSelector } from "react-redux";
import eventBus from "../../services/eventBus";
import { newlineChars } from "pdf-lib";
import GlobalModel from "../../components/common/GlobalModel";
import usePagination from "../../hooks/usePagination";
import { setProjectId } from "../../slices/localVariablesSlice";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import Pagination from "../../components/common/Pagination";

const EmployeeList = () => {
  const selectedProjectId = useSelector(
    (store) => store.localVariables.projectId
  );
  const { projectNames, loading: projectLoading, fetchData } = useProjectName();

  const dispatch = useDispatch();

  const [showInactive, setShowInactive] = useState(false);
  const Manage_Employee = useHasUserPermission(MANAGE_EMPLOYEES);

  const {
    data: employees,
    isLoading: loading,
    error,
    refetch: recallEmployeeData,
  } = useEmployeesByOrganization(showInactive);

  const [employeeList, setEmployeeList] = useState([]);
  const [modelConfig, setModelConfig] = useState();
  const [EmpForManageRole, setEmpForManageRole] = useState(null);
  // const [currentPage, setCurrentPage] = useState(1);
  // const [itemsPerPage] = useState(ITEMS_PER_PAGE);
  const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
  const [searchText, setSearchText] = useState("");
  const [filteredData, setFilteredData] = useState([]);
  const [showModal, setShowModal] = useState(false);
  const [selectedEmployeeId, setSelecedEmployeeId] = useState(null);
  const [IsDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [selectedEmpFordelete, setSelectedEmpFordelete] = useState(null);
  const [employeeLodaing, setemployeeLodaing] = useState(false);
  const ViewTeamMember = useHasUserPermission(VIEW_TEAM_MEMBERS);
  const { mutate: suspendEmployee, isPending: empLodaing } = useSuspendEmployee(
    {
      setIsDeleteModalOpen,
      setemployeeLodaing,
    }
  );

  useEffect(() => {
    if (selectedProjectId === null) {
      dispatch(setProjectId(projectNames[0]?.id));
    }
  }, [selectedProjectId]);
  const navigate = useNavigate();

  const applySearchFilter = (data, text) => {
    if (!text) {
      return data;
    }

    const lowercasedText = text.toLowerCase().trim();

    return data.filter((item) => {
      const firstName = item.firstName || "";
      const middleName = item.middleName || "";
      const lastName = item.lastName || "";

      const fullName = `${firstName} ${middleName} ${lastName}`
        .toLowerCase()
        .trim()
        .replace(/\s+/g, " ");

      const email = item.email?.toLowerCase() || "";
      const phoneNumber = item.phoneNumber?.toLowerCase() || "";
      const jobRole = item.jobRole?.toLowerCase() || "";

      return (
        fullName.includes(lowercasedText) ||
        email.includes(lowercasedText) ||
        phoneNumber.includes(lowercasedText) ||
        jobRole.includes(lowercasedText)
      );
    });
  };

  const handleSearch = (e) => {
    const value = e.target.value;
    setSearchText(value);
    setCurrentPage(1);
  };

  const displayData = searchText ? filteredData : employeeList;
  const { currentPage, totalPages, currentItems, paginate, setCurrentPage } =
    usePagination(displayData, ITEMS_PER_PAGE);
  const openModal = () => {
    setIsCreateModalOpen(true);
  };

  const handleConfigData = (config) => {
    setModelConfig(config);
  };

  const tableRef = useRef(null);
  const handleExport = (type) => {
    if (!currentItems || currentItems.length === 0) return;

    switch (type) {
      case "csv":
        exportToCSV(currentItems, "employees");
        break;
      case "excel":
        exportToExcel(currentItems, "employees");
        break;
      case "pdf":
        exportToPDF(currentItems, "employees");
        break;
      case "print":
        printTable(tableRef.current);
        break;
      default:
        break;
    }
  };

  const handleAllEmployeesToggle = (e) => {
    const isChecked = e.target.checked;
    setShowInactive(false);
    // setShowAllEmployees(isChecked);
  };

  const handleEmployeeModel = (id) => {
    setSelecedEmployeeId(id);
    setShowModal(true);
  };

  const handleOpenDelete = (employee) => {
    setSelectedEmpFordelete(employee);
    setIsDeleteModalOpen(true);
  };
  useEffect(() => {
    const filtered = applySearchFilter(employeeList, searchText);
    setFilteredData(filtered);
  }, [searchText, employeeList]);
  useEffect(() => {
    if (!loading && Array.isArray(employees)) {
      const sorted = [...employees].sort((a, b) => {
        const nameA = `${a.firstName || ""}${a.middleName || ""}${
          a.lastName || ""
        }`.toLowerCase();
        const nameB = `${b.firstName || ""}${b.middleName || ""}${
          b.lastName || ""
        }`.toLowerCase();
        return nameA?.localeCompare(nameB);
      });

      setEmployeeList((prevList) => {
        const prevJSON = JSON.stringify(prevList);
        const nextJSON = JSON.stringify(sorted);
        if (prevJSON !== nextJSON) {
          return sorted;
        }
        return prevList;
      });

      setFilteredData((prev) => {
        const prevJSON = JSON.stringify(prev);
        const nextJSON = JSON.stringify(sorted);
        if (prevJSON !== nextJSON) {
          return sorted;
        }
        return prev;
      });

      setCurrentPage((prevPage) => (prevPage !== 1 ? 1 : prevPage));
    }
  }, [loading, employees, selectedProjectId, showInactive]);

  const handler = useCallback(
    (msg) => {
      if (employees.some((item) => item.id == msg.employeeId)) {
        setEmployeeList([]);
        recallEmployeeData(showInactive);
      }
    },
    [employees, showInactive, showInactive, selectedProjectId] // Add all relevant dependencies
  );

  useEffect(() => {
    eventBus.on("employee", handler);
    return () => eventBus.off("employee", handler);
  }, [handler]);

  return (
    <>
      {EmpForManageRole && (
        <GlobalModel
          isOpen={EmpForManageRole}
          closeModal={() => setEmpForManageRole(null)}
        >
          <ManageEmp
            employeeId={EmpForManageRole}
            onClosed={() => setEmpForManageRole(null)}
          />
        </GlobalModel>
      )}

      {showModal && (
        <GlobalModel
          isOpen={showModal}
          size="lg"
          closeModal={() => setShowModal(false)}
        >
          <ManageEmployee
            employeeId={selectedEmployeeId}
            onClosed={() => setShowModal(false)}
          />
        </GlobalModel>
      )}

      {IsDeleteModalOpen && (
        <ConfirmModal
          isOpen={IsDeleteModalOpen}
          type="delete"
          header={
            selectedEmpFordelete?.isActive
              ? "Suspend Employee"
              : "Reactivate Employee"
          }
          message={`Are you sure you want to ${
            selectedEmpFordelete?.isActive ? "suspend" : "reactivate"
          } this employee?`}
          onSubmit={(id) =>
            suspendEmployee({
              employeeId: id,
              active: !selectedEmpFordelete.isActive,
            })
          }
          onClose={() => setIsDeleteModalOpen(false)}
          loading={employeeLodaing}
          paramData={selectedEmpFordelete.id}
        />
      )}

      <div className="container-fluid">
        <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Employees", link: null },
          ]}
        ></Breadcrumb>

        {ViewTeamMember ? (
          // <div className="row">
          <div className="card p-1 page-min-h">
            <div className="card-datatable table-responsive pt-5 mx-5 py-10">
              <div
                id="DataTables_Table_0_wrapper"
                className="dataTables_wrapper dt-bootstrap5 no-footer"
              >
                <div className="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-3">
                  {/* Switches: All Employees + Inactive */}
                  <div className="d-flex flex-wrap align-items-center gap-3">
                    {/* All Employees Switch */}

                    {/* Show Inactive Employees Switch */}

                    <div className="form-check form-switch text-start">
                      <input
                        type="checkbox"
                        className="form-check-input"
                        role="switch"
                        id="inactiveEmployeesCheckbox"
                        checked={showInactive}
                        onChange={(e) => setShowInactive(e.target.checked)}
                      />
                      <label
                        className="form-check-label ms-0"
                        htmlFor="inactiveEmployeesCheckbox"
                      >
                        In-active Employees
                      </label>
                    </div>
                  </div>

                  {/* Right side: Search + Export + Add Employee */}
                  <div className="d-flex flex-wrap align-items-center justify-content-start justify-content-md-end gap-3 flex-grow-1">
                    {/* Search Input - ALWAYS ENABLED */}
                    <div className="dataTables_filter">
                      <label className="mb-0">
                        <input
                          type="search"
                          value={searchText}
                          onChange={handleSearch}
                          className="form-control form-control-sm"
                          placeholder="Search Employee"
                          aria-controls="DataTables_Table_0"
                        />
                      </label>
                    </div>

                    {/* Export Dropdown */}
                    <div className="dropdown">
                      <button
                        aria-label="Click me"
                        className="btn btn-sm btn-label-secondary dropdown-toggle"
                        type="button"
                        data-bs-toggle="dropdown"
                        aria-expanded="false"
                      >
                        <i className="bx bx-export me-2 bx-sm"></i>Export
                      </button>
                      <ul className="dropdown-menu">
                        <li>
                          <a
                            className="dropdown-item"
                            href="#"
                            onClick={() => handleExport("print")}
                          >
                            <i className="bx bx-printer me-1"></i> Print
                          </a>
                        </li>
                        <li>
                          <a
                            className="dropdown-item"
                            href="#"
                            onClick={() => handleExport("csv")}
                          >
                            <i className="bx bx-file me-1"></i> CSV
                          </a>
                        </li>
                        <li>
                          <a
                            className="dropdown-item"
                            href="#"
                            onClick={() => handleExport("excel")}
                          >
                            <i className="bx bxs-file-export me-1"></i> Excel
                          </a>
                        </li>
                        <li>
                          <a
                            className="dropdown-item"
                            href="#"
                            onClick={() => handleExport("pdf")}
                          >
                            <i className="bx bxs-file-pdf me-1"></i> PDF
                          </a>
                        </li>
                      </ul>
                    </div>

                    {/* Add Employee Button */}
                    {Manage_Employee && (
                      <button
                        className="btn btn-sm btn-primary"
                        type="button"
                        onClick={() => handleEmployeeModel(null)}
                      >
                        <i className="bx bx-plus-circle me-2"></i>
                        <span className="d-none d-md-inline-block">
                          Add New Employee
                        </span>
                      </button>
                    )}
                  </div>
                </div>

                <table
                  className="datatables-users table border-top dataTable no-footer dtr-column text-nowrap"
                  id="DataTables_Table_0"
                  aria-describedby="DataTables_Table_0_info"
                  ref={tableRef}
                >
                  <thead>
                    <tr>
                      <th
                        className="sorting sorting_desc"
                        tabIndex="0"
                        aria-controls="DataTables_Table_0"
                        rowSpan="1"
                        colSpan="2"
                        aria-label="User: activate to sort column ascending"
                        aria-sort="descending"
                      >
                        <div className="text-start ms-6">Name</div>
                      </th>
                      <th
                        className="sorting sorting_desc d-none d-sm-table-cell"
                        tabIndex="0"
                        aria-controls="DataTables_Table_0"
                        rowSpan="1"
                        colSpan="1"
                        aria-label="User: activate to sort column ascending"
                        aria-sort="descending"
                      >
                        <div className="text-start ms-5">Email</div>
                      </th>
                      <th
                        className="sorting sorting_desc d-none d-sm-table-cell"
                        tabIndex="0"
                        aria-controls="DataTables_Table_0"
                        rowSpan="1"
                        colSpan="1"
                        aria-label="User: activate to sort column ascending"
                        aria-sort="descending"
                      >
                        <div className="text-start ms-5">Contact</div>
                      </th>
                      <th
                        className="sorting sorting_desc  d-none  d-sm-table-cell"
                        tabIndex="0"
                        aria-controls="DataTables_Table_0"
                        rowSpan="1"
                        colSpan="1"
                        aria-label="User: activate to sort column ascending"
                        aria-sort="descending"
                      >
                        <div className="text-start ms-5">Designation</div>
                      </th>

                      <th
                        className="sorting  d-none  d-md-table-cell"
                        tabIndex="0"
                        aria-controls="DataTables_Table_0"
                        rowSpan="1"
                        colSpan="1"
                        aria-label="Plan: activate to sort column ascending"
                      >
                        Joining Date
                      </th>
                      <th
                        className="sorting"
                        tabIndex="0"
                        aria-controls="DataTables_Table_0"
                        rowSpan="1"
                        colSpan="1"
                        aria-label="Billing: activate to sort column ascending"
                      >
                        Status
                      </th>
                      <th
                        className={`sorting_disabled  ${
                          !Manage_Employee && "d-none"
                        }`}
                        rowSpan="1"
                        colSpan="1"
                        style={{ width: "50px" }}
                        aria-label="Actions"
                      >
                        Actions
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {loading && (
                      <tr>
                        <td colSpan={8}>
                          <p>Loading...</p>
                        </td>
                      </tr>
                    )}

                    {!loading &&
                    displayData?.length === 0 &&
                    (!searchText ) ? (
                      <tr>
                        <td colSpan={8} className="border-0 py-3">
                        <div className="py-4">
                            No Data Found
                        </div>
                        </td>
                      </tr>
                    ) : null}

                      {!loading &&
                    displayData?.length === 0 &&
                    (searchText ) ? (
                      <tr>
                        <td colSpan={8} className="border-0 py-3">
                          <div className="py-4">
                            {`No match record found ${searchText} `}
                          </div>
                        </td>
                      </tr>
                    ) : null}

                    {/* Render current items */}
                    {currentItems &&
                      !loading &&
                      currentItems.map((item) => (
                        <tr className="odd" key={item.id}>
                          <td className="sorting_1" colSpan={2}>
                            <div className="d-flex justify-content-start align-items-center user-name">
                              <Avatar
                                firstName={item.firstName}
                                lastName={item.lastName}
                              ></Avatar>
                              <div className="d-flex flex-column">
                                <a
                                  onClick={() =>
                                    navigate(`/employee/${item.id}`)
                                  }
                                  className="text-heading text-truncate cursor-pointer"
                                >
                                  <span className="fw-normal">
                                    {item.firstName} {item.middleName}{" "}
                                    {item.lastName}
                                  </span>
                                </a>
                              </div>
                            </div>
                          </td>
                          <td className="text-start  d-none  d-sm-table-cell">
                            {item.email ? (
                              <span className="text-truncate">
                                <i className="bx bxs-envelope text-primary me-2"></i>
                                {item.email}
                              </span>
                            ) : (
                              <span className="text-truncate text-italic">
                                -
                              </span>
                            )}
                          </td>
                          <td className="text-start  d-none  d-sm-table-cell">
                            <span className="text-truncate">
                              <i className="bx bxs-phone-call text-primary me-2"></i>
                              {item.phoneNumber}
                            </span>
                          </td>
                          <td className=" d-none  d-sm-table-cell text-start">
                            <span className="text-truncate">
                              <i className="bx bxs-wrench text-success  me-2"></i>
                              {item.jobRole || "Not Assign Yet"}
                            </span>
                          </td>

                          <td className=" d-none  d-md-table-cell">
                            {moment(item.joiningDate)?.format("DD-MMM-YYYY")}
                          </td>
                          <td>
                            {showInactive ? (
                              <span
                                className="badge bg-label-danger"
                                text-capitalized=""
                              >
                                Inactive
                              </span>
                            ) : (
                              <span
                                className="badge bg-label-success"
                                text-capitalized=""
                              >
                                Active
                              </span>
                            )}
                          </td>
                          {Manage_Employee && (
                            <td className="text-end">
                              <div className="dropdown">
                                <button
                                  className="btn btn-icon dropdown-toggle hide-arrow"
                                  data-bs-toggle="dropdown"
                                >
                                  <i className="bx bx-dots-vertical-rounded bx-md"></i>
                                </button>
                                <div className="dropdown-menu dropdown-menu-end">
                                  {/* View always visible */}
                                  <button
                                    onClick={() =>
                                      navigate(`/employee/${item.id}`)
                                    }
                                    className="dropdown-item py-1"
                                  >
                                    <i className="bx bx-detail bx-sm"></i> View
                                  </button>

                                  {/* If ACTIVE employee */}
                                  {item.isActive && (
                                    <>
                                      <button
                                        className="dropdown-item py-1"
                                        onClick={() =>
                                          handleEmployeeModel(item.id)
                                        }
                                      >
                                        <i className="bx bx-edit bx-sm"></i>{" "}
                                        Edit
                                      </button>

                                      {/* Suspend only when active */}
                                      {item.isActive && (
                                        <button
                                          className="dropdown-item py-1"
                                          onClick={() => handleOpenDelete(item)}
                                        >
                                          <i className="bx bx-task-x bx-sm"></i>{" "}
                                          Suspend
                                        </button>
                                      )}

                                      <button
                                        className="dropdown-item py-1"
                                        type="button"
                                        data-bs-toggle="modal"
                                        data-bs-target="#managerole-modal"
                                        onClick={() =>
                                          setEmpForManageRole(item.id)
                                        }
                                      >
                                        <i className="bx bx-cog bx-sm"></i>{" "}
                                        Manage Role
                                      </button>
                                    </>
                                  )}

                                  {/* If INACTIVE employee AND inactive toggle is ON */}
                                  {!item.isActive && showInactive && (
                                    <button
                                      className="dropdown-item py-1"
                                      onClick={() => handleOpenDelete(item)}
                                    >
                                      <i className="bx bx-refresh bx-sm me-1"></i>{" "}
                                      Re-activate
                                    </button>
                                  )}
                                </div>
                              </div>
                            </td>
                          )}
                        </tr>
                      ))}
                  </tbody>
                </table>

                {displayData?.length > 0 && (
                  <Pagination
                    currentPage={currentPage}
                    totalPages={totalPages}
                    onPageChange={paginate}
                  />
                )}
              </div>
            </div>
          </div>
        ) : (
          <div className="card">
            <div className="text-center">
              <i className="fa-solid fa-triangle-exclamation fs-5"></i>
              <p>
                Access Denied: You don't have permission to perform this action.
                !
              </p>
            </div>
          </div>
        )}
      </div>
    </>
  );
};

export default EmployeeList;
