import { useEffect, useState } from 'react';
import { z } from 'zod/mini';

import type { MappedContentLink } from '~/lib/songwhipApi/mapper';

import Page from '~/src/components/Page';
import PageMetadata from '~/src/components/PageMetadata';
import PagePlaceholder from '~/src/components/PagePlaceholder';
import useIsEnabled from '~/src/hooks/useIsEnabled';
import { useI18n } from '~/src/lib/i18n';
import { useAppRouter } from '~/src/lib/router2';
import { getContentLinkApi } from '~/src/lib/songwhipApi/contentLinks/get';
import { Features } from '~/src/store/session/types';
import { ContentLinkForm } from './components';

const editContentLinkPageQuerySchema = z.object({
  id: z.coerce.number().check(z.positive()),
});

export const EditContentLinkPage = () => {
  const { t } = useI18n('contentLinkEdit');

  const isEnabled = useIsEnabled(Features.CONTENT_LINKS);

  const router = useAppRouter();
  const query = router.getQuery(editContentLinkPageQuerySchema);

  const [contentLink, setContentLink] = useState<MappedContentLink>();
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (!isEnabled) return;

    const fetchContentLink = async () => {
      try {
        const result = await getContentLinkApi(query.id);
        setContentLink(result);
      } catch {
        // noop, error state is handled by showing an error message
        // in the UI if content link is missing
      } finally {
        setIsLoading(false);
      }
    };

    fetchContentLink();

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (!isEnabled) {
    router.replace('/catalog');
    return;
  }

  if (isLoading) return <PagePlaceholder isLoading={isLoading} />;

  if (!contentLink) {
    const error = new Error(t('failedToLoad'));
    return <PagePlaceholder withMenuButton error={error} />;
  }

  return (
    <Page>
      <PageMetadata noIndex title={t('header')} />
      <ContentLinkForm contentLink={contentLink} />
    </Page>
  );
};
