import React, { useContext, useState, useMemo, useCallback } from "react";
import api from "../../services/issueAPI";

const IssueContext = React.createContext();

export const IssueProvider = ({ children }) => {
  const [issue, setIssue] = useState({});
  const [issues, setIssues] = useState([]);
  const [totalIssues, setTotalIssues] = useState(0);

  const getIssue = useCallback(async (id, token) => {
    const result = await api.getIssue(id, token);
    if (result.error) throw new Error(`Get issue error. ${result.message}`);

    setIssue(result.data ?? []);
    return result;
  }, []);

  const getIssues = useCallback(async (search,token) => {
    const result = await api.getIssues(search,token);
    if (result.error) {
      setIssues([]);
      throw new Error(`Get issues error. ${result.message}`);
    }
    setIssues(result.data ?? []);
    if (result.total) {
      setTotalIssues(result.total);
    }
  }, []);

  const deleteIssue = useCallback(async (id, token) => {
    const result = await api.deleteIssue(id, token);
    if (result.error)
      throw new Error(`Delete issue error. ${result.message}`);
    return result;
  }, []);

  const value = useMemo(() => ({
    totalIssues,
    issue,
    issues,

    deleteIssue,
    getIssue,
    getIssues,
  }), [totalIssues, issue, issues, deleteIssue, getIssue, getIssues]);

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

export const useIssueContext = () => useContext(IssueContext);
