import * as React from 'react';

import { cx } from '../../utils/cx';
import { Icon } from '../Icon';

export type SwitchProps = {
  id: string;
  onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
  checked?: boolean;
  disabled?: boolean;
  label?: string;
  className?: string;
};

export const Switch = ({
  onChange,
  id,
  label = '',
  checked = false,
  disabled = false,
  className = '',
}: SwitchProps): JSX.Element => {
  return (
    <label className={className} htmlFor={id}>
      <div
        className={cx(
          'uc-relative uc-inline-block uc-align-middle uc-select-none uc-bg-transparent',
          disabled ? '' : 'uc-cursor-pointer'
        )}
      >
        <div
          className={cx(
            'uc-transition-colors uc-duration-300 uc-w-12 uc-h-6 uc-rounded-full uc-shadow-inner',
            checked ? (disabled ? 'uc-bg-swirl' : 'uc-bg-primary') : 'uc-bg-sand-dune'
          )}
        >
          <input
            id={id}
            name={id}
            type="checkbox"
            className="uc-sr-only"
            disabled={disabled}
            checked={checked}
            onChange={onChange}
          />
        </div>
        <div
          className={cx(
            'uc-transition-all uc-duration-300 uc-ease-in-out uc-absolute uc-top-0 uc-left-0 uc-w-6 uc-h-6 uc-bg-white uc-border-2 uc-rounded-full',
            checked ? (disabled ? 'uc-border-swirl' : 'uc-border-primary') : 'uc-border-sand-dune',
            checked ? 'uc-transform uc-translate-x-full' : ''
          )}
        ></div>
        <div
          aria-hidden
          className="uc-flex uc-absolute uc-h-full uc-w-full uc-top-0 uc-left-0 uc-pl-1.5 uc-pr-2 uc-items-center uc-justify-between uc-text-white"
        >
          <Icon
            name="check"
            size="md"
            className={`uc-transition-opacity uc-duration-300 ${checked ? 'uc-opacity-100' : 'uc-opacity-0'}`}
          />
          <Icon
            name="close"
            size="sm"
            className={`uc-transition-opacity uc-duration-300 ${checked ? 'uc-opacity-0' : 'uc-opacity-100'}`}
          />
        </div>
      </div>
      {label ? <span className="uc-ml-2 uc-cursor-pointer">{label}</span> : null}
    </label>
  );
};
