import {
  type FieldItemProps,
  type FormRadioGroupProps,
} from "@/components/tanstack-form-utils";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { type ReactNode } from "react";

function getDefaultValue<T>(value: T): string {
  return String((value as any).value ?? value);
}

function getDefaultLabel<T>(value: T): ReactNode {
  return (value as any).label ?? String(value);
}

function getDefaultDescription<T>(value: T): ReactNode {
  return (value as any).description ?? null;
}

export function BasicRadioGroup<R>({
  options,
  getLabel = getDefaultLabel<R>,
  getValue = getDefaultValue<R>,
  getDescription = getDefaultDescription<R>,
  ...props
}: FieldItemProps &
  FormRadioGroupProps & {
    placeholder?: string;
    options?: R[];
    getValue?: (r: R) => string;
    getLabel?: (r: R) => ReactNode;
    getDescription?: (r: R) => ReactNode;
  }) {
  return (
    <RadioGroup {...props}>
      {options?.map((item) => {
        const description = getDescription(item);
        return (
          <div key={getValue(item)} className="flex items-center gap-2">
            <RadioGroupItem
              id={`${props.id}:${getValue(item)}`}
              value={getValue(item)}
            />
            <Label
              className="cursor-pointer block space-y-0.5"
              htmlFor={`${props.id}:${getValue(item)}`}
            >
              <div className="font-normal">{getLabel(item)}</div>
              {description && (
                <div className="text-xs text-muted-foreground">
                  {description}
                </div>
              )}
            </Label>
          </div>
        );
      })}
    </RadioGroup>
  );
}
