"use client";

import cx from "classnames";
import React from "react";

import { Label } from "../Label";
import { FieldContext, FieldContextType } from "./FieldContext";

const CLASS_ROOT = "form-field__label";

export interface LabelContext {
  control?: { type?: string };
  controlId?: string;
  label?: React.ReactNode;
  labelAfter?: React.ReactNode;
}

const FieldLabel: React.FC = () => {
  const context = React.useContext(FieldContext) as FieldContextType | null;
  const control = context?.control;
  const controlId = context?.controlId ?? "";
  const label = context?.label;
  const labelAfter = context?.labelAfter;

  return (
    <>
      {labelAfter ? (
        <div className={CLASS_ROOT}>
          {control?.type !== "range" ? (
            <Label
              id={controlId ? `${controlId}-label` : undefined}
              htmlFor={controlId}
              className={!labelAfter ? CLASS_ROOT : undefined}
            >
              {label}
            </Label>
          ) : (
            <span
              id={controlId ? `${controlId}-label` : undefined}
              className={cx("label", {
                [CLASS_ROOT]: !labelAfter,
              })}
            >
              {label}
            </span>
          )}
          {labelAfter && <> {labelAfter}</>}
        </div>
      ) : control?.type !== "range" ? (
        <Label
          id={controlId ? `${controlId}-label` : undefined}
          htmlFor={controlId}
          className={CLASS_ROOT}
        >
          {label}
        </Label>
      ) : (
        <span
          id={controlId ? `${controlId}-label` : undefined}
          className={cx("label", {
            [CLASS_ROOT]: !labelAfter,
          })}
        >
          {label}
        </span>
      )}
    </>
  );
};

export { FieldLabel };
