import { buildStorageUrl } from "@/components/main/BaseUrl";
import React from "react";
import { cookies } from "next/headers";
import { User } from "@/types/types";
import Container from "@/components/elements/Container";
import ModelHead from "@/components/models/ModelPage/ModelHead";
import ModelContent from "@/components/models/ModelPage/ModelContent";
import ProfileVisitTracker from "@/components/explore/ProfileVisitTracker";
import { Metadata } from "next";
import { generatePageMetadata } from "@/utils/generatePageMetadata";
import { fetchApiJson } from "@/lib/api/fetchApiJson";
import {
  buildProfileJsonLd,
  buildProfileSeo,
} from "@/lib/buildProfileSeo";
import LocalePageShell from "@/components/i18n/LocalePageShell";
import { getServerLanguage } from "@/lib/i18n/server";
import { translateCommon } from "@/lib/i18n/translate";

interface IUserProps {
  params: Promise<{ username: string }>;
}

type UserWebResponse = { user?: User };

export const dynamic = "force-dynamic";

async function loadUser(username: string, token: string) {
  const { data } = await fetchApiJson<UserWebResponse>(
    `/users/get/web?user_name=${encodeURIComponent(username)}`,
    {
      headers: token ? { Authorization: `Bearer ${token}` } : {},
    }
  );
  return data?.user ?? null;
}

export async function generateMetadata({ params }: IUserProps): Promise<Metadata> {
  const { username } = await params;
  const token = (await cookies()).get("token")?.value || "";
  const lang = await getServerLanguage();

  try {
    const user = await loadUser(username, token);
    const seo = buildProfileSeo(user, username, lang);
    const profileImage = user?.profile_image
      ? buildStorageUrl(user.profile_image)
      : "/images/logo.png";

    const meta = generatePageMetadata({
      title: seo.title,
      ogTitle: seo.title,
      description: seo.description,
      path: seo.path,
      type: "profile",
      imageUrl: user ? profileImage : undefined,
      imageAlt: ("fullName" in seo ? seo.fullName : undefined) || username,
      index: seo.index,
      lang,
    });

    return {
      ...meta,
      title: { absolute: seo.title },
    };
  } catch {
    const seo = buildProfileSeo(null, username, lang);
    const meta = generatePageMetadata({
      title: seo.title,
      ogTitle: seo.title,
      description: seo.description,
      path: seo.path,
      type: "profile",
      index: false,
      lang,
    });

    return {
      ...meta,
      title: { absolute: seo.title },
    };
  }
}

async function UserPage({ params }: IUserProps) {
  const { username } = await params;
  const token = (await cookies()).get("token")?.value || "";
  const lang = await getServerLanguage();

  const user = await loadUser(username, token);

  if (!user) {
    return (
      <Container>
        <div className="py-20 text-center font-bold">
          {translateCommon(lang, "profile.userNotFound")}
        </div>
      </Container>
    );
  }

  if (user.blocked_you) {
    return (
      <Container>
        <div className="flex min-h-[50vh] flex-col items-center justify-center px-6 py-20 text-center">
          <div className="mb-4 flex h-20 w-20 items-center justify-center rounded-full bg-neutral-200 dark:bg-neutral-800">
            <span className="text-3xl text-neutral-400">🚫</span>
          </div>
          <h2 className="text-lg font-bold text-foreground">
            {translateCommon(lang, "profile.unavailable")}
          </h2>
          <p className="mt-2 max-w-sm text-sm text-neutral-500 dark:text-neutral-400">
            {translateCommon(lang, "profile.blockedByUser")}
          </p>
        </div>
      </Container>
    );
  }

  const seo = buildProfileSeo(user, username, lang);
  const profileImage = user.profile_image
    ? buildStorageUrl(user.profile_image)
    : undefined;

  const jsonLd = buildProfileJsonLd(
    { ...user, profile_image: profileImage },
    username,
    seo.profileUrl || `https://modstagram.com/users/${username}`,
    lang
  );

  return (
    <Container>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />

      <LocalePageShell>
        <article>
          {user._id ? <ProfileVisitTracker profileUserId={user._id} /> : null}
          <h1 className="sr-only">{seo.h1}</h1>

          <ModelHead
            item2={{
              postsCount: user.postsCount,
              followersCount: user.followersCount,
              followingCount: user.followingCount,
              allProjectsCount: user.allProjectsCount,
              successfulProjectsCount: user.successfulProjectsCount,
            }}
            user={user}
          />
          <ModelContent user={user} searchParams={{}} />
        </article>
      </LocalePageShell>
    </Container>
  );
}

export default UserPage;
