import React from "react";

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

import TicketSearch from "../TicketSearch/TicketSearch";
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 [spinning, setSpinning] = React.useState(false);
  const [newTicketModalOpen, setNewTicketModalOpen] = React.useState(false);
  const [openCount, setOpenCount] = React.useState(0);
  const [pendingCount, setPendingCount] = React.useState(0);
  const [closedCount, setClosedCount] = React.useState(0);
  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) => {
    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
        setValueTab={setValueTab}
        valueTab={valueTab}
        count={{ openCount, pendingCount, closedCount }}
      />

      <TicketSearch
        spinning={spinning}
        handleSearch={handleSearch}
        setNewTicketModalOpen={setNewTicketModalOpen}
      />

      <TicketsList
        status="open"
        updateCount={(v) => setOpenCount(v)}
        showAll={showAllTickets}
        selectedQueueIds={selectedQueueIds}
        searchParam={searchParam}
        valueTab={valueTab}
      />

      <TicketsList
        status="pending"
        updateCount={(v) => setPendingCount(v)}
        selectedQueueIds={selectedQueueIds}
        searchParam={searchParam}
        valueTab={valueTab}
      />
      <TicketsList
        status="closed"
        updateCount={(v) => setClosedCount(v)}
        selectedQueueIds={selectedQueueIds}
        searchParam={searchParam}
        valueTab={valueTab}
      />
      
      <NewTicketModal
        modalOpen={newTicketModalOpen}
        onClose={(e) => setNewTicketModalOpen(false)}
      />

    </TicketsManagerStyled>
  );
};

export default TicketsManager;
