import { useEffect, useRef, useState } from 'react';

import type { LookupServiceLinks } from '~/lib/songwhipApi/types';
import type { DialogBoxApi } from '~/src/components/DialogBox';
import type { ServiceLinkOverrideCallback } from '~/src/features/presave';
import type { SelectedAlbum } from '~/src/store/albums/types';

import locales from '~/locales/fragments/upgradePrerelease';
import DialogBox from '~/src/components/DialogBox';
import { DialogBoxHeader } from '~/src/components/DialogBox/DialogBoxHeader';
import PageError from '~/src/components/PageError';
import PageLoading from '~/src/components/PageLoading';
import { useI18n, useI18nStatic } from '~/src/lib/i18n';
import { formatErrorMessage } from '~/src/views/PrereleaseUpgradePage/utils';
import { useAddMissingLinks } from '../hooks/useAddMissingLinks';
import { AddMissingLinksContent } from './AddMissingLinksContent';

export const AddMissingLinksDialog = ({
  album,
  onClose,
}: {
  album: SelectedAlbum;
  onClose: () => void;
}) => {
  const dialogBoxRef = useRef<DialogBoxApi>(null);
  const [linksOverride, setLinksOverride] = useState<LookupServiceLinks>();
  const { t } = useI18n();
  const { t: _tUpgradePrereleases } =
    useI18nStatic<'upgradePrerelease'>(locales);

  const close = () => dialogBoxRef.current?.close({});

  const { status, error, data, addLinks } = useAddMissingLinks({ album });

  useEffect(() => {
    void addLinks({ dryRun: true });
  }, [addLinks]);

  const handleLinksChange: ServiceLinkOverrideCallback = (service, link) => {
    setLinksOverride((prevLinks) => ({
      ...prevLinks,
      [service]: link,
    }));
  };

  const handleUpdate = async () => {
    const isUpdated = await addLinks({ dryRun: false, linksOverride });

    if (isUpdated) {
      // Close the dialog using the API - the album data will be updated in Redux automatically
      close();
    }
  };

  const renderContent = () => {
    if (
      status === 'fetchingPreview' ||
      (status === 'idle' && !data && !error)
    ) {
      return <PageLoading timeout={0} text={t('item.loadingLinks')} />;
    }

    if (data) {
      return (
        <AddMissingLinksContent
          album={album}
          preview={data}
          error={error}
          linksOverride={linksOverride}
          isUpdating={status === 'upgrading'}
          onUpdate={handleUpdate}
          onLinksChange={handleLinksChange}
        />
      );
    }

    return (
      <PageError
        error={{
          message: formatErrorMessage(t, error ?? { code: 'UNKNOWN_ERROR' }),
        }}
        withRefreshButton
      />
    );
  };

  return (
    <DialogBox
      apiRef={dialogBoxRef}
      onClose={onClose}
      testId="addMissingLinksDialog"
      renderHeader={({ close: closeFromRender }) => (
        <DialogBoxHeader
          title={t('item.addMissingLinks')}
          onCloseClick={closeFromRender}
          withShadow
        />
      )}
      renderContent={({ paddingX, paddingY }) => (
        <div style={{ padding: `${paddingY} ${paddingX}` }}>
          {renderContent()}
        </div>
      )}
    />
  );
};
