"use client";

import { useEditMode } from "./EditModeProvider";
import { CloudArrowUpIcon, XMarkIcon, PencilIcon } from "@heroicons/react/24/outline";

type Props = {
  page: string;
  getContent: () => unknown;
};

export function EditModeToggle({ page, getContent }: Props) {
  const { editMode, toggleEditMode, isDirty, setDirty } = useEditMode();

  async function handleSave() {
    const content = getContent();
    const res = await fetch("/api/content", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ page, content }),
    });
    if (res.ok) {
      setDirty(false);
      toggleEditMode();
    } else {
      alert("Greška pri čuvanju. Pokušajte ponovo.");
    }
  }

  return (
    <div className="fixed bottom-6 right-6 z-50 flex flex-col items-end gap-2">
      {editMode && isDirty && (
        <button
          onClick={handleSave}
          className="flex items-center gap-2 bg-green-600 hover:bg-green-700 text-white text-sm font-semibold px-4 py-2.5 rounded-full shadow-lg transition-colors"
        >
          <CloudArrowUpIcon className="w-4 h-4" /> Sačuvaj izmjene
        </button>
      )}
      <button
        onClick={toggleEditMode}
        className={
          editMode
            ? "flex items-center gap-2 bg-amber-500 hover:bg-amber-600 text-white text-sm font-semibold px-4 py-2.5 rounded-full shadow-lg transition-colors"
            : "flex items-center gap-2 bg-sky-600 hover:bg-sky-700 text-white text-sm font-semibold px-4 py-2.5 rounded-full shadow-lg transition-colors"
        }
      >
        {editMode ? <XMarkIcon className="w-4 h-4" /> : <PencilIcon className="w-4 h-4" />}
        {editMode ? "Zatvori uređivač" : "Uredi stranicu"}
      </button>
    </div>
  );
}
