import React, { useEffect } from 'react';
import { useAccountId, useAppStateDispatch, useDraft, useRankSource } from '../Context.js';
import useSWRImmutable from 'swr/immutable';
import { get } from './fetcher.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,
  );
  useEffect(() => {
    isLoading(getDraftIsLoading);

    if (getDraftError) {
      hasError(true);
      return;
    } else {
      hasError(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',
        },
      });
    }
  }, [getDraftData, getDraftError, getDraftIsLoading]);

  return <></>;
};

export default DraftFetcher;
