/* eslint-disable @typescript-eslint/no-explicit-any */
import Link from "next/link";
import { useEffect, useRef, useState } from "react";
import AddEditFrom from "./AddEditForm";
import BottomSheetModal from "../../Modal/BottomSheetModal";
import HourGlassLoader from "../../Loader/Loader";
import { getStaff, updateStaffStatus } from "../../../Api/CustomerApi";
import { getFormattedAddress } from "../../../lib/Helper";
import Swal from "sweetalert2";
import NoData from "../../NoDataContainer/NoData";

export default function AddUsersIndex() {
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const dropdownRef = useRef<HTMLDivElement | null>(null);
  const [addUserModal, setAddUserModal] = useState(false);
  const [editUser, setEditUser] = useState<any>({});
  const [users, setUsers] = useState<any>([]);
  const [activeMenu, setActiveMenu] = useState<number | null>(null);
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        dropdownRef.current &&
        !dropdownRef.current.contains(event.target as Node)
      ) {
        setActiveMenu(null);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, []);
  const fetchOrders = async () => {
    setIsLoading(true);
    try {
      const staffList = await getStaff();
      setUsers(staffList);
    } catch (error) {
      console.error("Failed to fetch staffs:", error);
    } finally {
      setIsLoading(false);
    }
  };
  const toggle = () => {
    setAddUserModal(!addUserModal);
    if (addUserModal) {
      setEditUser(null);
      fetchOrders();
    }
  };
  useEffect(() => {
    fetchOrders();
  }, []);
  const handleEdit = (item: any) => {
    setEditUser(item);
    toggle();
  };
  const handleChangeStatus = async (item: any) => {
    try {
      setIsLoading(true);
      const response = await updateStaffStatus(item?.id, {
        is_active: item?.isActive ? false : true,
      });
      if (response?.status) {
        await fetchOrders();
        Swal.fire({
          icon: "success",
          title: "Status Updated",
          text: response?.message,
          customClass: {
            confirmButton: "delybell-primary px-4",
            cancelButton: "delybell-dark",
          },
        });
      } else
        Swal.fire({
          icon: "error",
          title: "Error",
          text: response?.message,
          customClass: {
            confirmButton: "delybell-primary px-4",
            cancelButton: "delybell-dark",
          },
        });
    } catch (error) {
      console.error("Failed to change status of staff:", error);
    } finally {
      setIsLoading(false);
    }
  };
  // const handleChangePassword = () => {
  //   try {
  //   } catch (error) {
  //     console.error("Failed to change password of staff:", error);
  //   } finally {
  //     setIsLoading(false);
  //   }
  // };

  return (
    <>
      {isLoading && <HourGlassLoader />}
      <div className="page-content innerPageWrap ordersPageWrap oder-list-page">
        <div className="header header-fixed header-logo-app innerHeader">
          <a className="header-title header-subtitle">Staff</a>
          <Link href="/dashboard" className="header-icon header-icon-1">
            <i className="fas fa-chevron-left" />
          </Link>
          <button
            type="button"
            className="color-theme show-on-theme-light header-icon header-icon-2 font-16"
            onClick={() => setAddUserModal(true)}
          >
            <i className="fa fa-user-plus" />
          </button>
        </div>

        <div className="innerContentWrap orders-list mt-4">
          <div className="card card-style bg-transparent pb-0 m-0 rounded-0 overflow-visible">
            <div className="content m-0">
              <div className="row my-orders-row">
                {users?.length > 0 ? users?.map((user: any, index: any) => (
                  <div key={index} className="col-lg-3 order-list-box">
                    <div className="card card-style mb-4 overflow-visible">
                      <div className="content">
                        <div className="maindiv">
                          <div className="w-100">
                            <div className="d-float-center justify-content-between">
                              <h6 className="font-500 font-14 mb-2 d-float-center">
                                {user?.employeeId}
                              </h6>
                              <div>
                                <span
                                  title="Last Login"
                                  className={`badge ${user?.isActive ? "delybell-blue" : "delybell-yellow"} rounded-xl font-12 px-2 me-3`}
                                >
                                  {user?.isActive ? "Active" : "In Active"}
                                </span>
                                <div className="dropdown order-view-dropdown float-end">
                                  <button
                                    className="dropdown-toggle"
                                    type="button"
                                    data-bs-toggle="dropdown"
                                    aria-expanded="false"
                                    onClick={(e) => {
                                      e.preventDefault();
                                      setActiveMenu(user.id);
                                    }}
                                  >
                                    <i className="fa fa-ellipsis-v" />
                                  </button>
                                  {activeMenu === user.id && (
                                    <div
                                      ref={dropdownRef}
                                      className="dropdown-menu show"
                                      style={{
                                        position: "absolute",
                                        right: 0,
                                        top: "100%",
                                        zIndex: 1000,
                                      }}
                                    >
                                      <ul className="list-unstyled mb-0">
                                        <li>
                                          <a
                                            className="dropdown-item font-14"
                                            href="#"
                                            onClick={() => handleEdit(user)}
                                          >
                                            <i className="fa fa-edit me-1" />{" "}
                                            Edit
                                          </a>
                                        </li>
                                        <li>
                                          <a
                                            className="dropdown-item font-14"
                                            href="#"
                                            onClick={() =>
                                              handleChangeStatus(user)
                                            }
                                          >
                                            <i
                                              className={`fa ${
                                                user?.isActive
                                                  ? "fa-toggle-on"
                                                  : "fa-toggle-off"
                                              } me-1`}
                                            />{" "}
                                            {user?.isActive
                                              ? "In Active"
                                              : "Active"}{" "}
                                          </a>
                                        </li>
                                        {/* <li>
                                          <a
                                            className="dropdown-item font-14"
                                            href="#"
                                            onClick={handleChangePassword}
                                          >
                                            <i className="fa fa-shield-alt me-1" />{" "}
                                            Change Password
                                          </a>
                                        </li> */}
                                      </ul>
                                    </div>
                                  )}
                                </div>
                              </div>
                            </div>
                            <h6 className="font-700 font-15 text-dark">
                              {user?.firstName} {user?.lastName}
                            </h6>
                            <h6 className="font-400 font-13 opacity-50 mb-2">
                              <i className="fa fa-map-marker me-1" />{" "}
                              {getFormattedAddress(user)}
                            </h6>
                            <div className="order-info-icons d-float-center justify-content-between">
                              <div className="d-float-center gap-15">
                                <div className="d-float-center box">
                                  <i className="fa fa-phone me-1" />
                                  <span>{user?.phone}</span>
                                </div>
                                <div className="d-float-center weight">
                                  <i className="fa fa-envelope me-1" />
                                  <span>{user?.email}</span>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                )) : (<NoData />)}
              </div>
            </div>
          </div>
        </div>
      </div>
      {addUserModal && (
        <BottomSheetModal show={addUserModal} onHide={toggle} header={false}>
          <AddEditFrom toggle={toggle} editUser={editUser} />
        </BottomSheetModal>
      )}
    </>
  );
}
