import React from "react";
import { Controller, Control } from "react-hook-form";
import Toggle from "../../../../global/Toggle";

interface Props {
  control: Control;
  fieldName?: string;
  defaultStatus?: boolean;
  controlled?: boolean;
  controlledCheck?: boolean;
  checkedLabel?: string;
  uncheckedLabel?: string;
  withoutLabel?: boolean;
  onChangeFn?: (value: boolean) => void;
  disabled?: boolean;
  moreCss?: string;
}

const SwitchInput: React.FC<Props> = ({
  control,
  fieldName,
  defaultStatus = false,
  controlled = false,
  controlledCheck,
  checkedLabel,
  uncheckedLabel,
  withoutLabel,
  onChangeFn,
  moreCss,
  disabled = false,
}) => {
  const mapToBoolean = (value: number) => value === 1;
  const mapToNumber = (value: boolean) => (value ? 1 : 2);

  return (
    <Controller
      name={fieldName || "status"}
      control={control}
      defaultValue={mapToNumber(defaultStatus)}
      render={({ field }) => (
        <div
          className={
            withoutLabel
              ? ""
              : `flex gap-4 font-semibold rounded border-2 border-stroke bg-transparent pt-2.5 pb-1 px-3 text-black ${moreCss}`
          }
        >
          <Toggle
            id={Math.random().toString()}
            checked={controlled ? controlledCheck : mapToBoolean(field.value)}
            onChange={(value: boolean) => {
              const newValue = mapToNumber(value);
              if (controlled) {
                onChangeFn && onChangeFn(value);
              } else {
                field.onChange(newValue);
                onChangeFn && onChangeFn(value);
              }
            }}
            disabled={disabled}
          />
          {!withoutLabel && (
            <p>
              {controlled
                ? controlledCheck
                  ? checkedLabel || "Active"
                  : uncheckedLabel || "Inactive"
                : mapToBoolean(field.value)
                ? checkedLabel || "Active"
                : uncheckedLabel || "Inactive"}
            </p>
          )}
        </div>
      )}
    />
  );
};

export default SwitchInput;
