import type { ReactNode } from "react";
import FieldLabel from "./help/FieldLabel";
import { helpForFieldLabel } from "../utils/fieldHelp";
import { usePlatformLanguage } from "../i18n/LanguageContext";

type ToggleSwitchProps = {
  label: ReactNode;
  activeLabel?: ReactNode;
  inactiveLabel?: ReactNode;
  checked: boolean;
  onChange?: (checked: boolean) => void;
  disabled?: boolean;
  help?: ReactNode;
};

export default function ToggleSwitch({ label, activeLabel, inactiveLabel, checked, onChange, disabled = false, help }: ToggleSwitchProps) {
  const { translateText } = usePlatformLanguage();
  const hasStateLabels = activeLabel !== undefined || inactiveLabel !== undefined;
  const renderedLabel = typeof label === "string" ? translateText(label) : label;
  const renderedInactiveLabel = typeof inactiveLabel === "string" ? translateText(inactiveLabel) : inactiveLabel;
  const renderedActiveLabel = typeof activeLabel === "string" ? translateText(activeLabel) : activeLabel;
  const inputLabel = typeof renderedLabel === "string" ? renderedLabel : undefined;
  return (
    <label className={`toggle-switch-row ${disabled ? "disabled" : ""}`}>
      <input
        className="toggle-switch-input"
        type="checkbox"
        checked={checked}
        disabled={disabled}
        aria-label={inputLabel}
        onChange={(event) => onChange?.(event.target.checked)}
      />
      {hasStateLabels && inactiveLabel !== undefined &&
      <span className="toggle-switch-state-label is-inactive" data-selected={!checked || undefined}>
          {renderedInactiveLabel}
        </span>
      }
      <span className="toggle-switch-track" aria-hidden="true"><span className="toggle-switch-thumb" /></span>
      {hasStateLabels && activeLabel !== undefined &&
      <span className="toggle-switch-state-label is-active" data-selected={checked || undefined}>
          {renderedActiveLabel}
        </span>
      }
      {!hasStateLabels &&
      <span className="toggle-switch-copy">
        <FieldLabel className="toggle-switch-label" help={help ?? helpForFieldLabel(label)}>{renderedLabel}</FieldLabel>
      </span>
      }
    </label>
  );
}
