"use server";

import React from "react";
import Link from "next/link";
import { notFound } from "next/navigation";
import styles from "@/app/(Admin)/dashboard/(Posts Zone)/posts/[slug]/add.module.css";

import { getPostMaintainById } from "@/models/posts.model";
import { getPostCategories, getTags } from "@/models/term";
import { getJadwalPelatihanByPostId } from "@/models/jadwal.pelatihan";
import { isEmptyObject, spliceObject } from "@/utils/library";
import { decodeAccessToken, getCookieByName } from "@/utils/cookie";

import PostEditor from "@/components/administrator/PostEditor/post.editor";
import PostLock from "@/providers/post.lock";

// icons
import { BsArrowLeft } from "react-icons/bs";
import { getBridgeSettings } from "@/models/settings";

const PostManagement = async ({ params, searchParams }) => {
  try {
    const { slug: _id } = await params;
    const query = await searchParams;
    const postData = await getPostMaintainById(_id);
    const categories = await getPostCategories();
    const tags = await getTags();
    const jadwalPelatihanList = await getJadwalPelatihanByPostId(_id);

    const tab = parseInt(query?.tab) || 0;

    // id lock
    const lockPost = await getCookieByName("lockPost");
    const user = await decodeAccessToken();

    const currentSatus = postData?.status;
    if (isEmptyObject(postData)) return notFound();

    // splice post_lock
    const { selected: posteditor_meta, spliced: data } = spliceObject(
      postData,
      ["post_lock", "post_publish"],
      false
    );

    const post_lock = {
      own: posteditor_meta?.post_lock?.user_id === user?.data?._id,
      user: posteditor_meta?.post_lock?.user,
      postLockData: posteditor_meta.post_lock,
    };

    // get Join Bridge
    const joinBridge = await getBridgeSettings();

    console.log({ joinBridge });

    return (
      <div className={styles.container}>
        <div className={styles.header}>
          <Link
            className={styles.back}
            href="/dashboard/posts">
            <BsArrowLeft /> back
          </Link>
        </div>
        <div className={styles.body}>
          <PostLock>
            <PostEditor
              uid={lockPost}
              tab={tab}
              post_lock={post_lock}
              post_publish={posteditor_meta?.post_publish}
              currentSatus={currentSatus}
              categories={categories}
              tags={tags}
              data={data}
              additional_data={{
                jadwalPelatihanList,
                joinBridge: joinBridge?.endpoints,
              }}
            />
          </PostLock>
        </div>
      </div>
    );
  } catch (error) {
    console.log({ error });
    notFound();
  }
};

export default PostManagement;
