import * as Icons from "./Icons";
import { useState, Children } from "react";

export function EditToggle({ children }: React.PropsWithChildren) {
  const [isEditing, setIsEditing] = useState(false);
  const editChildren = (
    Children.toArray(children) as React.ReactElement[]
  ).filter((c) => c.type === Editing);
  const nonEditChildren = (
    Children.toArray(children) as React.ReactElement[]
  ).filter((c) => c.type !== Editing);

  return (
    <div className="relative">
      <div className="absolute right-0 top-0 z-50">
        <button
          type="button"
          className="inline-flex items-center justify-center rounded-full bg-violet-600 hover:bg-violet-700 text-white w-8 h-8 focus:outline-none focus:ring-2 focus:ring-violet-400"
          aria-label={isEditing ? "Exit edit mode" : "Enter edit mode"}
          onClick={() => setIsEditing(!isEditing)}
        >
          <Icons.Edit />
        </button>
      </div>
      {isEditing ? editChildren : nonEditChildren}
    </div>
  );
}

export const Editing = ({ children }: React.PropsWithChildren) => (
  <>{children}</>
);
export const NotEditing = ({ children }: React.PropsWithChildren) => (
  <>{children}</>
);
