import React, { useEffect, useState } from "react";
import "./toggle-styles.scss";
import { ToggleProps } from "@app/models/components";
import { Oval } from "react-loader-spinner";

const Toggle: React.FC<ToggleProps> = ({
  options,
  defaultValue,
  onChange,
  disabled,
  isLoading,
  label,
  icon,
}) => {
  const [selected, setSelected] = useState(defaultValue);
  const handleToggle = (value: string) => {
    setSelected(value);
    onChange(value);
  };

  useEffect(() => {
    setSelected(defaultValue);
  }, [defaultValue]);

  return (
    <div className="toggle-root-container">
      {label && (
        <label>
          {label} {icon && icon}
        </label>
      )}
      <div className={`toggle-container ${disabled ? "toggle-disabled" : ""}`}>
        {options?.map((option, index) => (
          <div
            key={option.value}
            className={`toggle-option ${
              selected === option.value ? "active" : ""
            }`}
            onClick={() => handleToggle(option.value)}
          >
            <div className="toggle-label">
              {isLoading && selected === option.value ? (
                <Oval
                  height={26}
                  width={26}
                  color={disabled ? "#615D5D" : "#8134af"}
                  wrapperStyle={{}}
                  wrapperClass=""
                  visible={true}
                  ariaLabel="oval-loading"
                  secondaryColor={disabled ? "#615D5D" : "#8134af"}
                  strokeWidth={6}
                  strokeWidthSecondary={6}
                />
              ) : (
                option?.icon
              )}
              <span>{option.label}</span>
            </div>
          </div>
        ))}
        <div
          className="toggle-slider"
          style={{
            left: selected === options[0].value ? "0%" : "50%",
          }}
        />
      </div>
    </div>
  );
};

export default Toggle;
