import React from "react";

import TicketsManagerStyled from "./TicketsManager.style";
import TicketsTabs from "./TicketsTabs/TicketsTabs";
import TicketsList from "../../TicketsList/TicketsList";
import NewTicketModal from "../../NewTicketModal";

import { AuthContext } from "../../../context/Auth/AuthContext";

const TicketsManager = () => {
  const [valueTab, setValueTab] = React.useState("open");
  const [searchParam, setSearchParam] = React.useState("");

  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 || []);

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

    clearTimeout(searchTimeout);

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

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

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

  return (
    <TicketsManagerStyled>
      <TicketsTabs setValueTab={setValueTab} valueTab={valueTab} />
      {/*Input and add new call*/}
      <div style={{ display: "flex", flexDirection: "row", justifyContent: "center" }}>
        <input type="text" style={{ width: "100%", margin: "0 6px" }} onChange={handleSearch} />
        <button onClick={() => setNewTicketModalOpen(true)}>+</button>
      </div>
      {/*Input and add new call*/}
      
      <TicketsList
        status={valueTab}
        selectedQueueIds={selectedQueueIds}
        searchParam={searchParam}
      />

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

export default TicketsManager;
