import React, { createContext, useContext, useState } from 'react';
import type { LinkError } from '../types/link-error';
import { LinkPayEnvironment } from '../types/link-pay-environment';
import type { SessionResult } from '../types/session-result';

interface LinkPayContextConfig {
  sessionKey: string;
  setSessionKey: (sessionKey: string) => void;
  environment: LinkPayEnvironment;
  setEnvironment: (environment: LinkPayEnvironment) => void;
  redirectUrl: string;
  setRedirectUrl: (redirectUrl: string) => void;
  sessionResult: SessionResult | null;
  setSessionResult: (sessionResult: SessionResult | null) => void;
  failure: LinkError | null;
  setFailure: (error: LinkError | null) => void;
}

const linkPayContextDefaultValues: LinkPayContextConfig = {
  sessionKey: '',
  setSessionKey() {
    return;
  },
  environment: LinkPayEnvironment.sandbox,
  setEnvironment() {
    return;
  },
  redirectUrl: '',
  setRedirectUrl() {
    return;
  },
  sessionResult: null,
  setSessionResult() {
    return;
  },
  failure: null,
  setFailure() {
    return;
  },
};

const LinkPayContext = createContext<LinkPayContextConfig>(
  linkPayContextDefaultValues
);

interface LinkPayContextProviderProps {
  children?: React.ReactNode;
}

export const useLinkPayContext = () => {
  return useContext(LinkPayContext);
};

export const LinkPayContextProvider = ({
  children,
}: LinkPayContextProviderProps) => {
  const [sessionKey, setSessionKey] = useState('');
  const [environment, setEnvironment] = useState(LinkPayEnvironment.sandbox);
  const [redirectUrl, setRedirectUrl] = useState('');
  const [sessionResult, setSessionResult] = useState<SessionResult | null>(
    null
  );
  const [failure, setFailure] = useState<LinkError | null>(null);

  const value = {
    sessionKey,
    setSessionKey,
    environment,
    setEnvironment,
    redirectUrl,
    setRedirectUrl,
    sessionResult,
    setSessionResult,
    failure,
    setFailure,
  };

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