"use client"

import { Label, RadioGroup } from "react-aria-components"
import { useController, useFormContext } from "react-hook-form"

import { Typography } from "@scandic-hotels/design-system/Typography"

import { trackUpdatePaymentMethod } from "@/utils/tracking"

import type { ReactNode } from "react"

interface PaymentOptionsGroupProps {
  name: string
  label?: string
  children: ReactNode
  className?: string
}

export default function PaymentOptionsGroup({
  name,
  label,
  children,
  className,
}: PaymentOptionsGroupProps) {
  const { control } = useFormContext()

  const {
    field: { value, onChange },
  } = useController({
    name,
    control,
  })

  const handleChange = (newValue: string) => {
    onChange(newValue)
    trackUpdatePaymentMethod("", newValue)
  }

  return (
    <RadioGroup value={value} onChange={handleChange} className={className}>
      {label ? (
        <Typography variant="Title/Overline/sm">
          <Label>{label}</Label>
        </Typography>
      ) : null}
      {children}
    </RadioGroup>
  )
}
