import React, { FC } from "react";
import cx from "classnames"
import './Switch.scss';
import { SwitchProps } from "./Switch.types";
import { Label } from "..";
import { v4 as uuidv4 } from 'uuid';
import { useLocale } from "../../hooks/useLocale";

export const Switch: FC<SwitchProps> = ({
  id = uuidv4(),
  name,
  checked,
  onChange,
  optionLabels = ["", ""],
  isDisabled,
  style,
  label,
  value = "false",
  size = "dynamic",
  labelPosition = "right",
  backgroundColorClass = ""
}) => {

  const labels = {
    yes: useLocale(optionLabels[0]),
    no: useLocale(optionLabels[1])
  }

  let styleTogle = 'toggle';

  let newStyle = { ...style || {} };

  let L0 = optionLabels[0]?.length;
  let L1 = optionLabels[1]?.length;

  let lettersCount = L0 >= L1 ? L0 : L1;
  let switchWidth = (lettersCount * 13) + 86;
  switchWidth = switchWidth < 54 ? 54 : switchWidth;

  let slider_width = { width: `${switchWidth}px` } as React.CSSProperties;

  if (size == "dynamic") {
    newStyle = { ...newStyle, ...slider_width };
  }

  return (
    <>
      <div className={cx("gtc-rc-toggle-wrap", `gtc-rc-${labelPosition}-label-wrap`)} style={newStyle} data-testid="SwitchWrapJest">
        <div
          className={cx(`gtc-rc-${styleTogle}-switch`, `gtc-rc-${size}-switch`)}
          data-testid="SwitchDivJest"
        >
          <input
            type="checkbox"
            name={name}
            data-testid="SwitchJest"
            className={`gtc-rc-${styleTogle}-switch-checkbox`}
            id={id}
            value={value}
            checked={checked}
            onChange={e => {
              if (onChange) {
                onChange(e.target.checked);
              }
            }}
            disabled={isDisabled}
          />
          {
            id &&
            <label className={`gtc-rc-${styleTogle}-switch-label`}
              htmlFor={id}
              tabIndex={isDisabled ? -1 : 1}
            >
              <span
                className={cx(`gtc-rc-${styleTogle}-switch-inner`, isDisabled && `gtc-rc-${styleTogle}-switch-disabled`, backgroundColorClass)}
                data-yes={optionLabels[0]}
                data-no={optionLabels[1]}
                tabIndex={-1}
              />
              <span
                className={cx(`gtc-rc-${styleTogle}-switch-switch`, isDisabled && `gtc-rc-${styleTogle}-switch-disabled`)}
                tabIndex={-1}
              />
            </label>
          }
        </div>

        {label &&
          <div className="gtc-rc-switch-label-div">
            <Label data-testid="LabelJest">{label}</Label>
          </div>
        }
      </div>
    </>
  );
}