"use client"
import { useRouter } from "next/navigation"
import { useCallback, useEffect } from "react"
import { Controller, FormProvider, useForm } from "react-hook-form"
import { useIntl } from "react-intl"

import { profile } from "@scandic-hotels/common/constants/routes/myPages"
import { Button } from "@scandic-hotels/design-system/Button"
import { RadioButtonsGroup } from "@scandic-hotels/design-system/Form/RadioButtonsGroup"
import { Tooltip } from "@scandic-hotels/design-system/Tooltip"
import { Typography } from "@scandic-hotels/design-system/Typography"

import ProfilingConsentAccordion from "@/components/MyPages/ProfilingConsent/Accordion"
import useLang from "@/hooks/useLang"
import { useUpdateProfilingConsent } from "@/hooks/useUpdateProfilingConsent"
import {
  trackConsentAction,
  trackConsentChange,
} from "@/utils/tracking/profilingConsent"

import styles from "./form.module.css"

interface ProfilingConsentProps {
  heading: string | null
  preamble: string | null
  consent?: boolean
}

export function ProfilingConsent({
  preamble,
  heading,
  consent,
}: ProfilingConsentProps) {
  const intl = useIntl()
  const router = useRouter()
  const lang = useLang()

  const options = [
    {
      consent: true,
      value: intl.formatMessage({
        id: "profilingConsent.accept",
        defaultMessage: "Accept",
      }),
      title: intl.formatMessage({
        id: "profilingConsent.yesIAccept",
        defaultMessage: "Yes, I would like to accept profiling!",
      }),
      text: intl.formatMessage({
        id: "profilingConsent.iConsentToScandicUsingMyInformation",
        defaultMessage:
          "I consent to Scandic using my information to give me even more personalized travel inspiration and offers from Scandic and trusted Scandic Friends partners. This means Scandic may use information about my interactions with Scandic Friends partners, and share details of my interactions with Scandic with those partners, to make the experience even more relevant to me.",
      }),
    },
    {
      consent: false,
      value: intl.formatMessage({
        id: "common.decline",
        defaultMessage: "Decline",
      }),
      title: intl.formatMessage({
        id: "profilingConsent.noDeclineProfiling",
        defaultMessage: "No, decline profiling",
      }),
      text: intl.formatMessage({
        id: "profilingConsent.receiveGeneralInformationMarketingOnly",
        defaultMessage: "Receive general information & marketing only.",
      }),
    },
  ]

  type AcceptPersonalizationForm = { consent: string }
  const form = useForm<AcceptPersonalizationForm>({
    defaultValues: {
      consent: options.find((option) => option.consent === consent)?.value,
    },
  })
  const {
    control,
    handleSubmit,
    formState: { isDirty },
  } = form

  const { initiateUpdateConsent, isLoading, isSuccess } =
    useUpdateProfilingConsent()
  const onSubmit = (data: AcceptPersonalizationForm) => {
    if (isDirty) {
      const cons = options.find(
        (option) => option.value === data.consent
      )?.consent
      if (cons !== undefined) {
        initiateUpdateConsent(cons)
        trackConsentChange({ from: consent, to: cons })
      }
    }
  }
  const backToProfile = useCallback(() => {
    router.push(profile[lang])
  }, [router, lang])

  useEffect(() => {
    if (isSuccess) backToProfile()
  }, [isSuccess, backToProfile])

  return (
    <FormProvider {...form}>
      <form onSubmit={handleSubmit(onSubmit)}>
        <div className={styles.container}>
          <Typography variant="Title/md" className={styles.title}>
            <h1>{heading}</h1>
          </Typography>
          <Typography variant="Body/Lead text">
            <p>{preamble}</p>
          </Typography>
          <div className={styles.form}>
            <fieldset className={styles.fieldset}>
              <legend className={styles.legend}>
                <Typography variant="Title/Subtitle/lg">
                  <p>
                    {intl.formatMessage({
                      id: "profilingConsent.profilingConsent",
                      defaultMessage: "Profiling consent",
                    })}
                  </p>
                </Typography>
                <Typography>
                  <p>
                    {intl.formatMessage({
                      id: "profilingConsent.updateAtAnyTime",
                      defaultMessage:
                        "You can update your preferences at any time. We respect your choices and will only use and store your data in accordance with your consent.",
                    })}
                  </p>
                </Typography>
              </legend>
              <Controller
                name="consent"
                control={control}
                render={({ field }) => (
                  <RadioButtonsGroup
                    options={options}
                    ariaLabel={intl.formatMessage({
                      id: "profilingConsent.acceptOrDecline",
                      defaultMessage: "Accept or decline personalization",
                    })}
                    onChange={(value: string) => field.onChange(value)}
                    defaultOption={options.find(
                      (option) => option.consent === consent
                    )}
                  />
                )}
              />
            </fieldset>
            <ProfilingConsentAccordion component="profile" />
          </div>
        </div>
        <div className={styles.buttons}>
          <Tooltip
            text={intl.formatMessage({
              id: "profilingConsent.tooltip.noChangesInPreferences",
              defaultMessage: "No changes in preferences have been made",
            })}
            position="top"
            arrow="center"
            isVisible={!isDirty}
          >
            <Button
              type="submit"
              typography="Body/Paragraph/mdBold"
              variant="Primary"
              color="Primary"
              size="Medium"
              isDisabled={!isDirty}
              isPending={isLoading}
            >
              {intl.formatMessage({
                id: "profilingConsent.save&update",
                defaultMessage: "Save & update preferences",
              })}
            </Button>
          </Tooltip>
          <Button
            type="button"
            typography="Body/Paragraph/mdBold"
            variant="Secondary"
            color="Primary"
            size="Medium"
            onClick={() => {
              backToProfile()
              trackConsentAction({
                position: "profile",
                name: "cancel",
              })
            }}
          >
            {intl.formatMessage({
              id: "common.cancel",
              defaultMessage: "Cancel",
            })}
          </Button>
        </div>
      </form>
    </FormProvider>
  )
}
