"use client";

import clsx from "clsx";

interface ToggleProps {
  checked: boolean;
  onChange: (value: boolean) => void;

  label?: string;
  description?: string;

  disabled?: boolean;

  size?: "sm" | "md" | "lg";

  activeColor?: string;
  inactiveColor?: string;

  className?: string;
}

export default function Toggle({
  checked,
  onChange,
  label,
  description,
  disabled = false,
  size = "md",
  activeColor = "bg-link-1",
  inactiveColor = "bg-link-1/10",
  className = "",
}: ToggleProps) {
  const sizes = {
    sm: {
      track: "h-5 w-9",
      thumb: "h-3.5 w-3.5",
      on: "translate-x-4",
      off: "translate-x-0",
    },
    md: {
      track: "h-7 w-12",
      thumb: "h-5 w-5",
      on: "translate-x-5",
      off: "translate-x-0",
    },
    lg: {
      track: "h-8 w-14",
      thumb: "h-6 w-6",
      on: "translate-x-6",
      off: "translate-x-0",
    },
  };

  const current = sizes[size];

  return (
    <div
      className={clsx(
        "flex items-center justify-between gap-4",
        className
      )}
    >
      {(label || description) && (
        <div>
          {label && (
            <h4 className="font-medium text-heading">
              {label}
            </h4>
          )}

          {description && (
            <p className="mt-1 text-sm text-gray-500">
              {description}
            </p>
          )}
        </div>
      )}

      <button
        type="button"
        role="switch"
        aria-checked={checked}
        disabled={disabled}
        onClick={() => !disabled && onChange(!checked)}
        className={clsx(
          "relative shrink-0 rounded-full transition-all duration-300",
          current.track,
          checked ? activeColor : inactiveColor,
          disabled && "cursor-not-allowed opacity-50"
        )}
      >
        <span
          className={clsx(
            "absolute left-1 top-1 rounded-full bg-white shadow-sm transition-transform duration-300",
            current.thumb,
            checked ? current.on : current.off
          )}
        />
      </button>
    </div>
  );
}