import clsx from "clsx";
import { ChevronRight } from "lucide-react";
import { useState } from "react";

function SettingsRow({
  icon: IconComponent,
  title,
  value,
  onClick,
  rightToggle,
  defaultOn = false,
}) {
  const [on, setOn] = useState(defaultOn);
  const interactive = !!onClick && !rightToggle;

  return (
    <div
      className={clsx(
        "w-full flex items-center gap-3 px-3.5 py-3 border-b border-line-subtle last:border-b-0 transition-colors duration-fast",
        interactive && "cursor-pointer hover:bg-hover"
      )}
    >
      {IconComponent && (
        <div className="w-7 h-7 rounded-md bg-elevated text-fg-secondary inline-flex items-center justify-center flex-shrink-0">
          <IconComponent size={14} strokeWidth={1.75} />
        </div>
      )}
      {interactive ? (
        <button
          type="button"
          onClick={onClick}
          className="flex-1 min-w-0 bg-transparent border-0 text-left cursor-pointer p-0"
        >
          <div className="text-[13px] font-medium text-fg truncate">{title}</div>
        </button>
      ) : (
        <div className="flex-1 min-w-0">
          <div className="text-[13px] font-medium text-fg truncate">{title}</div>
        </div>
      )}
      {value && (
        <div className="text-[12px] font-mono text-fg-secondary truncate max-w-[60%] text-right">
          {value}
        </div>
      )}
      {rightToggle ? (
        <button
          type="button"
          aria-label={`Toggle ${title}`}
          aria-pressed={on}
          onClick={(e) => {
            e.stopPropagation();
            setOn(!on);
          }}
          className={clsx(
            "relative w-9 h-5 flex-shrink-0 cursor-pointer border-0 rounded-full transition-colors duration-normal ease-out-expo",
            on ? "bg-accent" : "bg-overlay"
          )}
        >
          <span
            className="absolute top-[2px] w-4 h-4 rounded-full bg-fg transition-[left] duration-normal ease-out-expo"
            style={{ left: on ? 18 : 2 }}
          />
        </button>
      ) : (
        onClick && <ChevronRight size={14} strokeWidth={1.75} className="text-fg-tertiary" />
      )}
    </div>
  );
}

window.SettingsRow = SettingsRow;
