"use client";

import cx from "classnames";
import React from "react";
import { Bar, BarBreak, BarItem } from "../../Bar";
import { Control } from "./Control";
import { Description } from "./Description";
import { FieldContext, FieldContextType } from "./FieldContext";
import { FieldLabel } from "./Label";
import { Messages } from "./Messages";
import { FormTooltip } from "./Tooltip";
import { getControlId } from "./utils";

export interface InputFieldProps {
  className?: string;
  control: FieldContextType["control"];
  hint?: React.ReactNode;
  label?: React.ReactNode;
  labelAfter?: React.ReactNode;
  messages?: Array<{ type: string; text: string }>;
  tooltip?: React.ReactNode;
  [key: string]: any;
}

const CLASS_ROOT = "form-field";

const Field: React.FC<InputFieldProps> = ({
  className,
  control,
  hint,
  label,
  labelAfter,
  messages = [],
  tooltip,
  ...other
}) => {
  const isRadioCheck = ["radio", "checkbox"].includes(control?.type ?? "");
  const isToggle = control?.type === "checkbox" && control?.isToggle;

  const classes = cx(CLASS_ROOT, className, {
    [`${CLASS_ROOT}--radiocheck`]: isRadioCheck,
  });

  const controlId = getControlId(control ?? {});
  const context: FieldContextType = {
    control,
    hint,
    label,
    labelAfter,
    messages,
    tooltip,
    controlId,
    isRadioCheck,
  };

  return (
    <div className={classes} {...other}>
      <FieldContext.Provider value={context}>
        {isRadioCheck ? (
          isToggle ? (
            <>
              <Bar space={"small"}>
                <BarItem>
                  <Bar canWrap={false}>
                    <BarItem>
                      <Control className="mr-none" />
                    </BarItem>
                    <BarItem canShrink={true}>
                      <FieldLabel />
                      <FormTooltip id={controlId}>{tooltip}</FormTooltip>
                    </BarItem>
                  </Bar>
                </BarItem>
                <BarBreak />
                <BarItem className={"mt-none"}>
                  <Description hideLabel>
                    <Messages />
                  </Description>
                </BarItem>
              </Bar>
            </>
          ) : (
            <>
              <Control />
              <Description>
                <Messages />
              </Description>
            </>
          )
        ) : (
          <>
            <Description />
            <Control />
            <Messages />
          </>
        )}
      </FieldContext.Provider>
    </div>
  );
};

Field.displayName = "Field";

export { Field };
