"use client";

import React, { useState } from "react";
import { useRouter } from "next/navigation";
import { useSelector } from "react-redux";
import { selectUser } from "@/utils/store/features/ui/userdata.slice";
import usePostManagement from "@/hooks/usePostManagement";
import Loader from "@/components/web/Loader/loader";
import Button from "@/components/ui/Button/button";

/**
 *
 * @type {React.FC <{
 *    children?: React.ReactNode;
 *    className?: string;
 *    fontSize?: number;
 *    color?: string;
 *    getPost: Function;
 * }>}
 * @returns
 */
const NewPost = (props) => {
  const router = useRouter();
  const user = useSelector(selectUser);

  const [loading, setLoading] = useState(false);
  const { createPost } = usePostManagement();

  const getPost = (data) => {
    if (props.getPost && typeof props.getPost === "function")
      props.getPost(data);
  };

  return (
    <Button
      className={props.className}
      disabled={loading}
      style={{
        fontSize: `${props.fontSize || 16}px`,
        color: props.color || "#fff",
      }}
      onClick={async () => {
        setLoading(true);
        await createPost(user._id, (result) => {
          getPost(result);
          router.push(`/dashboard/posts/${result._id}`);
        });
        setLoading(false);
      }}>
      {loading && (
        <Loader
          width={props.fontSize || 16}
          color={props.color || "#fff"}
        />
      )}
      {props.children}
    </Button>
  );
};

export default NewPost;
