import type { FormPageConfig } from './types';

import Page from '~/src/components/Page';
import PageMetadata from '~/src/components/PageMetadata';
import { useApiMutation } from '~/src/hooks/useApi';
import { useI18n } from '~/src/lib/i18n';
import { createCustomPageApi } from '~/src/lib/songwhipApi/customPages';
import { CreateFlow } from '~/src/ui/components/createFlow';
import { ChooseArtistStage } from '../components/ChooseArtistStage';
import { buildFormPageLayout } from './buildFormPageLayout';
import { FormBuilderStage } from './stages/FormBuilderStage';
import { FormMetadataStage } from './stages/FormMetadataStage';
import { FormPrivacyStage } from './stages/FormPrivacyStage';

export const CreateFormPage = () => {
  const { t } = useI18n('formPage');
  const { trigger: createPage } = useApiMutation(createCustomPageApi);

  const handleSubmit = async (data: FormPageConfig) => {
    const { rosterArtistId, name, message, type, fields, submit } = data;

    if (!rosterArtistId) {
      throw new Error('rosterArtistId is required');
    }

    if (!name) {
      throw new Error('name is required');
    }

    const page = await createPage({
      rosterArtistId,
      name,
      pageType: 'form',
      config: {
        layout: buildFormPageLayout({ name, message, type, fields, submit }),
      },
    });

    window.location.href = `/draft/${page.path}`;
  };

  return (
    <Page withGradient>
      <CreateFlow<FormPageConfig>
        onSubmit={handleSubmit}
        defaultData={{
          fields: [
            { type: 'preset', name: 'name' },
            { type: 'preset', name: 'email' },
          ],
        }}
        stages={[
          {
            id: 'artist',
            title: t('pickArtist'),
            Component: ChooseArtistStage as never,
            hideNextButton: true,
          },
          {
            id: 'metadata',
            title: t('step1Title'),
            Component: FormMetadataStage,
          },
          {
            id: 'form',
            title: t('step2Title'),
            Component: FormBuilderStage,
          },
          {
            id: 'terms',
            title: t('step3Title'),
            Component: FormPrivacyStage,
          },
        ]}
      />
      <PageMetadata title={t('createForm')} noIndex />
    </Page>
  );
};
