import React, {
  createContext,
  useContext,
  useState,
  useEffect,
  useRef,
  Dispatch,
  SetStateAction,
  PropsWithChildren,
} from 'react';
import {ConversationDrafts} from '@modules/chats/instances/ConversationDrafts';

// Context value type
type InputValueContextValue = [string, Dispatch<SetStateAction<string>>];

// Create context
const InputValueContext = createContext<InputValueContextValue | undefined>(
  undefined,
);

// Provider props interface
interface InputValueProviderProps extends PropsWithChildren {
  initialValue?: string;
  channel?: string;
}

// Provider component
export const InputValueProvider: React.FC<InputValueProviderProps> = ({
  children,
  channel,
  initialValue = '',
}) => {
  const inputValueState = useState<string>(() => {
    if (initialValue) {
      return initialValue;
    }
    if (channel) {
      return ConversationDrafts.get(channel);
    }
    return '';
  });
  const [value] = inputValueState;
  const valueRef = useRef(value);
  valueRef.current = value;

  useEffect(() => {
    if (!channel) {
      return;
    }
    return () => {
      ConversationDrafts.set(channel, valueRef.current);
    };
  }, [channel]);

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

// Custom hook to use the context
export const useInputValue = (): InputValueContextValue => {
  const context = useContext(InputValueContext);

  if (context === undefined) {
    throw new Error('useInputValue must be used within an InputValueProvider');
  }

  return context;
};

// Export context for advanced usage
export {InputValueContext};
