import { useRef } from 'react';
import { z } from 'zod/mini';

import type { FormApi, FormValues } from '~/src/components/Form';
import type { CreateFlowStage } from '../../components/CreateFlow/types';

import Box from '~/src/components/Box';
import Form from '~/src/components/Form';
import { DestinationInput } from '~/src/features/contentLink';
import { useListenOnEvent } from '~/src/hooks/useListenOnEvent';
import { useAppRouter } from '~/src/lib/router2';

interface DestinationLinkValues extends FormValues {
  destinationUrl: string;
}

const destinationLinkStageQuerySchema = z.object({
  destinationUrl: z.catch(z.optional(z.string()), undefined),
});

export const DestinationLinkStage: CreateFlowStage = ({ events }) => {
  const formApiRef = useRef<FormApi>(null);
  const router = useAppRouter();
  const query = router.getQuery(destinationLinkStageQuerySchema);

  useListenOnEvent(events, 'nextButtonPressed', () => {
    formApiRef.current?.submit();
  });

  return (
    <Box maxWidth="48rem" width="100%">
      <Form<DestinationLinkValues>
        testId="contentLinkDestinationForm"
        trackingId="contentLinkDestinationForm"
        apiRef={formApiRef}
        onSubmit={async ({ values }) => {
          await router.setQuery({
            stage: 'details',
            destinationUrl: values.destinationUrl,
          });
        }}
      >
        <DestinationInput initialValue={query.destinationUrl} />
      </Form>
    </Box>
  );
};
