import React, { PropsWithChildren } from 'react';
import { Category } from '@usercentrics/cmp-browser-sdk';

import { Status } from '../UsercentricsContext/types';
import { Decision } from './types';
import { DecisionsContext } from './DecisionsContext';
import { decisionsActions } from './decisionsContextActions';
import { decisionsReducer } from './decisionsContextReducer';

type Props = {
  categories: Category[];
  status: Status;
};

export const DecisionsProvider = ({ children, categories, status }: PropsWithChildren<Props>): JSX.Element => {
  const [decisions, dispatch] = React.useReducer(decisionsReducer, {});

  React.useEffect(() => {
    if (status === 'initializing') {
      return;
    }

    const newDecisions: Decision[] = categories.flatMap((catg) =>
      catg.services.map((service) => ({
        serviceId: service.id,
        categorySlug: catg.slug,
        status: service.consent.status,
      }))
    );

    dispatch(decisionsActions.initFromItems(newDecisions));
  }, [categories, status]);

  const value = {
    decisions,
    updateDecision: (serviceId: string, status: boolean) => dispatch(decisionsActions.update({ serviceId, status })),
  };

  return <DecisionsContext.Provider value={value}>{children}</DecisionsContext.Provider>;
};
