import { useNavigate } from "react-router-dom";
import { Container, Paper, Stack, Text, Title } from "@mantine/core";
import { useTranslation } from "react-i18next";
import { OperationsFormContent } from "../../profile/components/OperationsFormContent";

/**
 * Where a fresh applicant lands after declaring themselves. Someone who says
 * "I own a vessel" came here to register, so they are taken to that service's
 * own page — which lists what they already hold and starts the application —
 * rather than dropped straight into the wizard with no way back. A seafarer
 * goes to `/profile` instead — registration is built from the profile
 * (`RequireSeafarerProfile`), and a brand-new signup has none of it yet, so
 * sending them straight to the wizard would only bounce them back here.
 * Seafarer wins when both are ticked; the other page is one nav click away.
 *
 * Seafarer goes to its own registration page, whose Identity Details step
 * collects the profile answers itself — no detour via `/profile`. Seafarer
 * wins when both are ticked; the other form is one nav click away.
 *
 * SEAFARER_REGISTRATION is listed before ENDORSEMENT_SEAFARER deliberately:
 * `nextStepFor` takes the first key that matches, and an applicant who ticked
 * both belongs in registration first — the endorsement application refuses
 * submission until that registration is accepted.
 */
const NEXT_STEP: Record<string, string> = {
  SEAFARER_REGISTRATION: "/seafarer-registration",
  VESSEL_REGISTRATION: "/vessel-registration",
  ENDORSEMENT_SEAFARER: "/endorsements",
};

function nextStepFor(selectedKeys: string[]): string {
  const key = Object.keys(NEXT_STEP).find((k) => selectedKeys.includes(k));
  return key ? NEXT_STEP[key] : "/dashboard";
}

/**
 * The one thing a new applicant is asked for beyond their credentials.
 *
 * It is a step of its own rather than a field on the signup form because the
 * licence catalogue it offers is not readable without a session — signup
 * issues the token, and this is the first screen behind it. An applicant who
 * arrived before modes existed lands here once, for the same reason.
 *
 * Saving is what completes it: `RequireOperations` stops redirecting here as
 * soon as the profile has at least one mode.
 */
export function OperationsOnboardingPage() {
  const { t } = useTranslation();
  const navigate = useNavigate();

  return (
    <Container size="sm" py="xl">
      <Stack gap="lg">
        <div>
          <Title order={3}>{t("onboarding.operations.title")}</Title>
          <Text size="sm" c="dimmed" mt={4}>
            {t("onboarding.operations.body")}
          </Text>
        </div>
        <Paper p="xl" shadow="sm" radius="lg" withBorder>
          <OperationsFormContent
            onSaved={(keys) => navigate(nextStepFor(keys))}
          />
        </Paper>
      </Stack>
    </Container>
  );
}

export default OperationsOnboardingPage;
