import React, { createContext, useContext, useState, useEffect } from 'react';
import { removeSpecialCharacter } from '../utils/postalCode';
import { getFullLocalStorage } from '../utils/localStorage';
import type { RegionalizationProps } from '../types/RegionalizationProps';
import type { ContextProps, View, DeliveryProps } from '../types/ContextProps';
import type { Address } from '../types/Address';
import type { PikcupPointType } from '../types/PikcupPointType';

const RegionalizationContext = createContext<
  (RegionalizationProps & ContextProps) | null
>(null);

export const RegionalizationContextProvider = ({
  setMethod,
  setPickupName,
  setCity,
  setUf,
  setPickupTimes,
  pricesAndHours,
  setModalOpen,
  inputPostalCode,
  setInputPostalCode,
  sendPostalCode,
  status,
  setStatus,
  pickupPoints,
  titleText,
  moreInfosText,
  textBackButton,
  confirmButton,
  editAddress,
  delivery,
  deliveryPrice,
  pickup,
  regionalizeCatalog,
  children,
}: RegionalizationProps & ContextProps) => {
  const [internalMethod, setInternalMethod] = useState<string | undefined>();
  const [view, setView] = useState<View>('PostalCodeInputScreen');
  const [postalCode, setPostalCode] = useState<string | undefined>('');
  const [address, setAddress] = useState<Address>();
  const [pickupAddress, setPickupAddress] = useState<PikcupPointType>();
  const [deliveryRequestInfos, setDeliveryRequestInfos] = useState<
    undefined | DeliveryProps
  >();

  const pickupTimes = {
    openingTime:
      pickupAddress?.businessHours.businessHoursWeek.openingTime.slice(0, 2) ??
      '',
    closingTime:
      pickupAddress?.businessHours.businessHoursWeek.closingTime.slice(0, 2) ??
      '',
  };

  const asyncSendPostalCode = async () => {
    setStatus({ loading: true, message: 'Carregando...' });
    const {
      isValid,
      address: addressRequest,
      deliveryInfos: deliveryData,
    } = await sendPostalCode();

    if (isValid) {
      setStatus({ loading: false });
      setInternalMethod('delivery');
      setAddress(addressRequest);
      setStatus({});
      setPostalCode(inputPostalCode);
      setDeliveryRequestInfos(deliveryData);
      setView('ConfirmScreen');
    }
  };

  const postalCodeValidation = () => {
    const validatePostalCode = /\d{8}$/.test(
      removeSpecialCharacter(inputPostalCode)
    );

    if (validatePostalCode) {
      asyncSendPostalCode();
    } else {
      setStatus({
        status: 'failed',
        loading: false,
        message: 'Informe um Cep valido ',
      });
    }
  };

  useEffect(() => {
    setPostalCode(getFullLocalStorage()?.userAddressInfos?.postalCode);
    setMethod?.(getFullLocalStorage()?.regionalized);
    setDeliveryRequestInfos(getFullLocalStorage()?.deliveryInfos);
  }, []);

  return (
    <RegionalizationContext.Provider
      value={{
        setMethod,
        setPickupName,
        setCity,
        setUf,
        setPickupTimes,
        pickupTimes,
        pricesAndHours,
        setModalOpen,
        inputPostalCode,
        setInputPostalCode,
        sendPostalCode,
        status,
        setStatus,
        pickupPoints,
        titleText,
        moreInfosText,
        textBackButton,
        confirmButton,
        editAddress,
        delivery,
        pickup,
        view,
        setView,
        postalCodeValidation,
        address,
        pickupAddress,
        setPickupAddress,
        deliveryRequestInfos,
        postalCode,
        internalMethod,
        setInternalMethod,
        regionalizeCatalog,
        deliveryPrice,
      }}
    >
      {children}
    </RegionalizationContext.Provider>
  );
};

export const useRegionalizationContext = () => {
  const context = useContext(RegionalizationContext);

  if (!context) {
    throw new Error(
      'useRegionalizationContext must be used within a RegionalizationContextProvider'
    );
  }

  return context;
};
