import React, { useEffect } from 'react';
import { useAccountId, useAppStateDispatch, useDraft, useRankSource } from '../Context.js';
import useSWRImmutable from 'swr/immutable';
import { get } from './fetcher.js';
import { useEffectEvent } from '../hooks/useEffectEvent.js';

// Fetches a draft and populates the app context.
const DraftFetcher = ({
  isLoading = (_) => true,
  hasError = (_) => false,
}: {
  isLoading: (_: boolean) => void;
  hasError: (_: boolean) => void;
}) => {
  const dispatch = useAppStateDispatch();
  const accountId = useAccountId();
  const draft = useDraft();
  const rankSource = useRankSource();

  const {
    data: getDraftData,
    error: getDraftError,
    isLoading: getDraftIsLoading,
  } = useSWRImmutable(
    draft.id && !draft.lastUpdated
      ? `/conductor/proxy/v3/accounts/${accountId}/drafts/${draft.id}/writing-assistant`
      : null,
    get,
  );

  const onError = useEffectEvent((error) => {
    hasError(error);
  });
  const onLoading = useEffectEvent((loading) => {
    isLoading(loading);
  });

  useEffect(() => {
    onLoading(getDraftIsLoading);

    if (getDraftError) {
      onError(true);
      return;
    } else {
      onError(false);
    }

    if (draft.id && !draft.lastUpdated) {
      if (getDraftData?.id && getDraftData?.id === draft.id && getDraftData?.updated) {
        dispatch({
          type: 'updateDraft',
          draft: {
            title:
              getDraftData.draftTitle ??
              `Untitled Canvas Draft: ${(getDraftData.phrases ?? []).join(', ')}`,
            lastUpdated: getDraftData.updated,
            metaDescription: getDraftData.metaDescription ?? '',
            bodyCopy: getDraftData.bodyCopy ?? '',
          },
        });
      }
      if (getDraftData?.rankSourceId && rankSource?.id !== getDraftData?.rankSourceId) {
        dispatch({ type: 'setRankSource', rankSource: { id: getDraftData.rankSourceId } });
      }

      if (getDraftData?.phrases?.length) {
        dispatch({
          type: 'setKeywords',
          keywords: getDraftData.phrases,
        });
      }
      if (getDraftData?.competitorUrls?.length) {
        dispatch({
          type: 'setCompetitorUrls',
          competitorUrls: getDraftData.competitorUrls,
        });
      }
    }

    // Set default Rank Source.
    if ((!draft.id || !getDraftData?.rankSourceId) && !rankSource.id) {
      dispatch({
        type: 'setRankSource',
        rankSource: {
          id: 1,
          description: 'Google (US / English)',
          isoLocale: 'en_US',
        },
      });
    }
  }, [
    dispatch,
    draft.id,
    draft.lastUpdated,
    rankSource.id,
    getDraftData,
    getDraftError,
    getDraftIsLoading,
  ]);

  return <></>;
};

export default DraftFetcher;
