import React from "react";

import TicketsManagerStyled from "./TicketsManager.style";
import TicketsTabs from "./TicketsTabs/TicketsTabs";
import TicketsList from "./TicketsList/TicketsList";
import NewTicketModal from "../../NewTicketModal";
import useTickets from "../../../hooks/useTickets";
import { AuthContext } from "../../../context/Auth/AuthContext";
import TicketSearch from "../TicketSearch/TicketSearch";

const TicketsManager = () => {
  const [valueTab, setValueTab] = React.useState("open");
  const [searchParam, setSearchParam] = React.useState("");
  const [spinning, setSpinning] = React.useState(false);
  const [newTicketModalOpen, setNewTicketModalOpen] = React.useState(false);
  const [showAllTickets, setShowAllTickets] = React.useState(false);
  const { user } = React.useContext(AuthContext);
  const userQueueIds = user.queues.map((q) => q.id);
  const [selectedQueueIds, setSelectedQueueIds] = React.useState(userQueueIds || []);
  const { tickets } = useTickets({
    searchParam
  });

  let searchTimeout;
  const handleSearch = (e) => {
    setSpinning(true);
    const searchedTerm = e.target.value.toLowerCase();

    clearTimeout(searchTimeout);

    searchTimeout = setTimeout(() => {
      setSearchParam(searchedTerm);
      setSpinning(false);
    }, 200);

    if (searchedTerm === "") {
      setSearchParam(searchedTerm);
      return;
    }
  };

  React.useEffect(() => {
    if (user.profile.toUpperCase() === "ADMIN") {
      setShowAllTickets(true);
    }
  }, [user.profile]);

  return (
    <TicketsManagerStyled>
      <TicketsTabs tickets={tickets} setValueTab={setValueTab} valueTab={valueTab} />
      <TicketSearch
        spinning={spinning}
        handleSearch={handleSearch}
        setNewTicketModalOpen={setNewTicketModalOpen}
      />
      <TicketsList
        showAll={showAllTickets}
        status={valueTab}
        selectedQueueIds={selectedQueueIds}
        searchParam={searchParam}
      />

      <NewTicketModal
        modalOpen={newTicketModalOpen}
        onClose={(e) => setNewTicketModalOpen(false)}
      />
    </TicketsManagerStyled>
  );
};

export default TicketsManager;
