"use client";
import Loader from "@/components/Loader";
import {Button} from "@/components/ui/button";
import {
  useGetPrivacyPolicy,
  useUpdatePrivacyPolicy,
} from "@/hooks/privacy-policy";
import {handleAxiosError} from "@/lib/utils";
import dynamic from "next/dynamic";
import React, {Suspense, useEffect, useRef, useState} from "react";
import {toast} from "react-toastify";
const RichTextEditor = dynamic(() => import("@/components/TextEditor"), {
  ssr: false,
});

type RichTextEditorHandle = {
  getContent: () => string;
};

export default function Page() {
  const editorRef = useRef<RichTextEditorHandle>(null); 
  const [editorContent, setEditorContent] = useState<string>("");

  const {mutateAsync} = useUpdatePrivacyPolicy();
  const {data, isLoading} = useGetPrivacyPolicy();
  const handleSave = async () => {
    if (editorRef.current) {
      const content = editorRef.current.getContent(); 
      setEditorContent(content); 

      try {
        const {message} = await mutateAsync(content);
        toast.success(message);
      } catch (error) {
        toast.error(handleAxiosError(error));
      }
    }
  };

  useEffect(() => {
    console.log(data)
    setEditorContent(data?.data?.content);
  }, [isLoading, data]);

  return (
    <div className="p-4">
      <h1 className="text-center font-bold my-5 text-xl">متن Privacy Policy</h1>
      <div>
        {(data?.data || !isLoading) && (
          <Suspense fallback={<Loader />}>
            <RichTextEditor ref={editorRef} value={editorContent} />
          </Suspense>
        )}
      </div>
      <div className="mt-5">
        <Button onClick={handleSave}>ثبت تغییرات</Button>
      </div>
    </div>
  );
}
