"use client";
import {
  createContext,
  useReducer,
  useState,
  useCallback,
  useMemo,
  useContext,
} from "react";

const reducer = (state, action) => {
  switch (action.type) {
    case "CHANGE_ACTIVE_TAB":
      return state.map((call, index) => ({
        ...call,
        active: index === action.index_call,
      }));
    case "CHANGE_LIST":
      return [...action.new_list];
    case "CHANGE_ACTIVE_CATEGORY_ID":
      return state.map((call) =>
        call.id === action.tab_id
          ? { ...call, active_category_id: action.category_id }
          : call,
      );
    default:
      return state;
  }
};

export const CallContext = createContext(null);

export const CallProvider = ({ children }) => {
  const [openCallDialog, setOpenCallDialog] = useState(false);
  const [activeCall, setActiveCall] = useState(0);
  const [calls, dispatch] = useReducer(reducer, []);

  const changeActiveTab = useCallback((index_call) => {
    dispatch({ type: "CHANGE_ACTIVE_TAB", index_call });
  }, []);

  const changeList = useCallback((new_list) => {
    dispatch({ type: "CHANGE_LIST", new_list });
  }, []);

  const changeActiveCategoryId = useCallback((tab_id, category_id) => {
    dispatch({ type: "CHANGE_ACTIVE_CATEGORY_ID", tab_id, category_id });
  }, []);

  const changeActiveTabCall = (newValue) => {
    changeActiveTab(newValue);
    setActiveCall(newValue);
  };

  const newCall = useCallback(
    (data) => {
      const newCall = {
        id: data.id,
        phone_number: data.phone_number,
        date: new Date(),
        active: true,
        active_category_id: null,
      };
      const newList = [...calls, newCall];
      changeList(newList);
      changeActiveTabCall(newList.length - 1);
    },
    [calls],
  );

  const closeCall = useCallback(
    (id) => {
      const index = calls.findIndex((answer) => answer.id === id);
      const newIndex = index === 0 ? 0 : index - 1;
      const newList = [...calls];
      newList.splice(index, 1);
      if (newList.length !== 0) {
        newList[newIndex].active = true;
        changeActiveTabCall(newIndex);
      }
      changeList(newList);
    },
    [calls],
  );

  const contextValue = useMemo(
    () => ({
      openCallDialog,
      setOpenCallDialog,
      calls,
      newCall,
      closeCall,
      activeCall,
      setActiveCall,
      changeActiveCategoryId,
      changeActiveTabCall,
    }),
    [openCallDialog, calls, activeCall],
  );

  return (
    <CallContext.Provider value={contextValue}>{children}</CallContext.Provider>
  );
};

export const useCall = () => useContext(CallContext);
