import { BASE_URL, IMAGE_BASE_URL, 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";

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

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

  try {
    const res = await fetch(`${BASE_URL}/users/get/web?user_name=${username}`, {
      cache: "no-store",
      headers: { Authorization: token ? `Bearer ${token}` : "" },
    });
    const data = await res.json();
    const user = data?.user as User;

    if (!user) {
      return { title: `${username} | مدستاگرام`, robots: "noindex" };
    }

    if (user.blocked_you) {
      return {
        title: "پروفایل در دسترس نیست | مدستاگرام",
        robots: "noindex, nofollow",
      };
    }

    const fullName = `${user.first_name || ""} ${user.last_name || ""}`.trim();
    const city = user.city?.name || "ایران";
    const expertise = user.expertise || "متخصص";
    const bio = user.bio || "پروفایل و نمونه‌کارهای حرفه‌ای در مدستاگرام";

    const title = `${fullName} - ${username} - ${expertise} - ${city} - مدستاگرام`;
    const description = `${expertise} - ${city} - ${bio}`.slice(0, 160);
    const profileImage = user.profile_image ? buildStorageUrl(user.profile_image) : "/images/logo.png";

    return {
      title, // حفظ تایتل درخواستی شما
      description, // حفظ دیسکریپشن درخواستی شما
      robots: {
        index: true,
        follow: true,
        googleBot: {
          index: true,
          follow: true,
          "max-image-preview": "large",
          "max-snippet": -1,
        },
      },
      alternates: {
        canonical: `https://modstagram.com/users/${username}`,
      },
      openGraph: {
        title,
        description,
        url: `https://modstagram.com/users/${username}`,
        siteName: "مدستاگرام",
        images: [{ url: profileImage, width: 800, height: 600, alt: fullName }],
        locale: "fa_IR",
        type: "profile",
        firstName: user.first_name || undefined,
        lastName: user.last_name || undefined,
        username: username,
      },
      twitter: {
        card: "summary_large_image",
        title,
        description,
        images: [profileImage],
      },
    };
  } catch (e) {
    return { title: `${username} | مدستاگرام` };
  }
}

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

  const response = await fetch(
    `${BASE_URL}/users/get/web?user_name=${username}`,
    {
      cache: "no-store",
      headers: {
        Authorization: token ? `Bearer ${token}` : "",
      },
    }
  );

  const data = await response.json();
  const user = data.user as User;

  if (!user) {
    return (
      <Container>
        <div className="py-20 text-center font-bold">کاربر یافت نشد!</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">این پروفایل در دسترس نیست</h2>
          <p className="mt-2 max-w-sm text-sm text-neutral-500 dark:text-neutral-400">
            شما توسط این کاربر مسدود شده‌اید و امکان مشاهده پروفایل و پست‌های او وجود ندارد.
          </p>
        </div>
      </Container>
    );
  }

  const fullName = `${user.first_name || ""} ${user.last_name || ""}`.trim();

  // داده ساختاریافته (Schema) برای درک بهتر گوگل از ماهیت پروفایل
  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "Person",
    name: fullName,
    alternateName: username,
    description: user.bio,
    image: user.profile_image ? buildStorageUrl(user.profile_image) : undefined,
    jobTitle: user.expertise,
    address: {
      "@type": "PostalAddress",
      addressLocality: user.city?.name,
      addressCountry: "IR"
    },
    url: `https://modstagram.com/users/${username}`
  };

  return (
    <Container>
      {/* تزریق اسکریپت JSON-LD */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />

      <article>
        {user._id ? <ProfileVisitTracker profileUserId={user._id} /> : null}
        {/* H1 پنهان برای تقویت کلمات کلیدی بدون تغییر ظاهر */}
        <h1 className="sr-only">
          {fullName} - {user.expertise} در {user.city?.name}
        </h1>

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

export default UserPage;