import { Metadata } from "next";
import { fetchPostById } from "@/api/fetchPostById";
import PostFeedView, { PostFeedSearchParams } from "@/components/posts/PostFeedView";
import { buildStorageUrl } from "@/components/main/BaseUrl";
import { generatePageMetadata } from "@/utils/generatePageMetadata";
import {
  buildPostPath,
  buildPostPublicUrl,
  buildPostSeoDescription,
  buildPostSeoTitle,
} from "@/lib/postSlug";
import { getSiteSeoMeta } from "@/lib/i18n/seo";
import { getServerLanguage } from "@/lib/i18n/server";
import { translateCommon } from "@/lib/i18n/translate";

type Props = {
  params: Promise<{ id: string; slug?: string[] }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
};

function pickQuery(
  sp: Record<string, string | string[] | undefined>,
  key: string
): string | undefined {
  const v = sp[key];
  return typeof v === "string" ? v : undefined;
}

function toFeedSearchParams(
  sp: Record<string, string | string[] | undefined>
): PostFeedSearchParams {
  return {
    feed: pickQuery(sp, "feed"),
    tab: pickQuery(sp, "tab"),
    userId: pickQuery(sp, "userId"),
    expertise: pickQuery(sp, "expertise"),
    province: pickQuery(sp, "province"),
    city: pickQuery(sp, "city"),
    userLevel: pickQuery(sp, "userLevel"),
    rateFilter: pickQuery(sp, "rateFilter"),
    hashtag: pickQuery(sp, "hashtag"),
    exploreFilter: pickQuery(sp, "exploreFilter"),
    subExpertise: pickQuery(sp, "subExpertise"),
    filter: pickQuery(sp, "filter"),
    lat: pickQuery(sp, "lat"),
    lng: pickQuery(sp, "lng"),
    q: pickQuery(sp, "q"),
  };
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { id } = await params;
  const lang = await getServerLanguage();
  const post = await fetchPostById(id);
  const title = post
    ? buildPostSeoTitle(post, lang)
    : translateCommon(lang, "postsMeta.defaultTitle");
  const description = post
    ? buildPostSeoDescription(post, lang)
    : translateCommon(lang, "postsMeta.defaultDescription");
  const ogImage = post?.files?.[0]?.path
    ? buildStorageUrl(post.files[0].path)
    : undefined;
  const authorName =
    post &&
    ([post.first_name, post.last_name].filter(Boolean).join(" ") ||
      post.user_name);

  const site = getSiteSeoMeta(lang);

  return generatePageMetadata({
    title,
    description,
    path: buildPostPath(id, post ?? undefined),
    type: "article",
    imageUrl: ogImage,
    imageAlt: post?.caption?.slice(0, 80) || translateCommon(lang, "postsMeta.defaultAlt"),
    keywords: [
      site.name,
      post?.expertise || "",
      authorName || "",
      translateCommon(lang, "postsMeta.keywordPost"),
      translateCommon(lang, "postsMeta.keywordModeling"),
      translateCommon(lang, "postsMeta.keywordBeauty"),
    ].filter(Boolean),
    publishedTime: post?.createdAt,
    modifiedTime: post?.updatedAt,
    lang,
  });
}

/** بدون await روی API — نمایش فوری از sessionStorage در PostFeedView */
export default async function PostPage({ params, searchParams }: Props) {
  const { id } = await params;
  const sp = await searchParams;
  const feedSearchParams = toFeedSearchParams(sp);

  return (
    <main className="min-h-[100dvh]">
      <PostFeedView
        initialPostId={id}
        showClose
        searchParams={feedSearchParams}
      />
    </main>
  );
}
