import { redirect } from "next/navigation"
import React from "react"

import { getProfileSafely } from "@/lib/trpc/memoizedRequests"

import { AlreadyLinkedError } from "../components/AlreadyLinkedError"
import { SASModal } from "../components/SASModal"
import { LinkAccountForm } from "./LinkAccountForm"

import type { LangParams, PageArgs } from "@/types/params"

export default async function SASxScandicLinkPage({
  params,
}: PageArgs<LangParams>) {
  const profile = await getProfileSafely()

  // TODO actually check if profile is already linked
  const alreadyLinked = false

  async function handleLinkAccount(dateOfBirth: string) {
    "use server"

    if (dateOfBirth !== profile?.dateOfBirth) {
      // TODO update users date of birth here
      console.log("updating date of birth")
    }

    return {
      redirectUrl: `/${params.lang}/sas-x-scandic/login?intent=link`,
      success: true,
    }
  }

  return alreadyLinked ? (
    <AlreadyLinkedError />
  ) : (
    <SASModal>
      <LinkAccountForm
        initialDateOfBirth={profile?.dateOfBirth ?? null}
        onSubmit={handleLinkAccount}
      />
    </SASModal>
  )
}
