import React, { useContext, useEffect, useState } from "react";
import api from "../../services/suppliersAPI";
import { LocalDateTimeString } from "../../utils/dates";

import {
  validateSupplier,
  validateEmail,
} from "../../utils/validationSupplier";
import { useSupplierContext } from "./SupplierContext";

const SupplierDetailsContext = React.createContext();

export const SupplierDetailsProvider = ({ children }) => {
  const { getSuppliers, suppliers } = useSupplierContext();
  const [busy, setBusy] = useState(false);
  const [contact, setContact] = useState("");
  const [company, setCompany] = useState("");
  const [address, setAddress] = useState("");
  const [phone, setPhone] = useState("");
  const [program, setProgram] = useState("");
  const [ecus, setECUs] = useState("");
  const [activated, setActivated] = useState(null);

  useEffect(() => {
    if (!suppliers || suppliers.length === 0) return;

    const supplier = suppliers[0];

    setContact(supplier?.contact || "");
    setCompany(supplier?.company || "");
    setAddress(supplier?.address || "");
    setPhone(supplier?.telephone || "");
    setProgram(supplier?.program || "");
    setECUs(supplier?.ecus.join(",") || "");
    setActivated(LocalDateTimeString(supplier?.activated));
  }, [suppliers]);

  const getSupplier = async (email, token) => {
    try {
      setBusy(true);
      const result = await getSuppliers({ email }, token);
      if (result?.error)
        throw new Error(`Get supplier error. ${result.message}`);
      return result;
    } finally {
      setBusy(false);
    }
  };

  const getECUs = () => {
    if (!ecus) return [];

    const items = ecus.split(",");

    return items.map((item) => item.trim());
  };

  const formData = (email) => ({
    contact,
    company,
    address,
    telephone: phone,
    email,
    program,
    ecus: getECUs(),
  });

  const activateSupplier = async (email, token) => {
    try {
      setBusy(true);
      validateEmail(email);

      const result = await api.activateSupplier(email, token);
      if (result.error)
        throw new Error(`Activate supplier error. ${result.message}`);

      setActivated(
        LocalDateTimeString(result.activate) || new Date().toDateString()
      );

      return result;
    } finally {
      setBusy(false);
    }
  };

  const updateSupplier = async (email, token) => {
    try {
      const supplier = formData(email);
      setBusy(true);
      validateSupplier(supplier);

      const result = await api.updateSupplier(email, supplier, token);
      if (result.error)
        throw new Error(`Update supplier error. ${result.message}`);
      return result;
    } finally {
      setBusy(false);
    }
  };

  const deleteSupplier = async (email, token) => {
    try {
      setBusy(true);
      validateEmail(email);

      const result = await api.deleteSupplier(email, token);
      if (result.error)
        throw new Error(`Delete supplier error. ${result.message}`);

      return result;
    } finally {
      setBusy(false);
    }
  };

  return (
    <SupplierDetailsContext.Provider
      value={{
        activated,
        busy,
        contact,
        company,
        address,
        phone,
        program,
        ecus,
        activateSupplier,
        deleteSupplier,
        getSupplier,
        updateSupplier,
        setContact,
        setCompany,
        setAddress,
        setPhone,
        setProgram,
        setECUs,
      }}
    >
      {children}
    </SupplierDetailsContext.Provider>
  );
};

export const useSupplierDetailsContext = () =>
  useContext(SupplierDetailsContext);
