import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { prisma } from "@/lib/db";
import { getCurrentUser } from "@/lib/auth/dal";
import { PhotoGallery } from "@/components/profile/PhotoGallery";
import { LikeButton } from "@/components/profile/LikeButton";
import { startConversation } from "@/lib/messages/actions";
import { buildPersonSchema } from "@/lib/seo/schema";
import { JsonLd } from "@/components/seo/JsonLd";
import { resolvePageMetadata } from "@/lib/seo/metadata";

type Props = {
  params: Promise<{ username: string }>;
};

async function getPublicProfile(username: string) {
  return prisma.profile.findUnique({
    where: { username },
    select: {
      userId: true,
      username: true,
      fullName: true,
      city: true,
      age: true,
      hobbies: true,
      cinemaTaste: true,
      musicTaste: true,
      bio: true,
      avatarPhoto: { select: { thumbUrl: true, altText: true } },
    },
  });
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { username } = await params;
  const profile = await getPublicProfile(username);
  if (!profile) return { title: "Profil Bulunamadı", robots: { index: false, follow: false } };

  return resolvePageMetadata(`/profil/${username}`, {
    title: profile.fullName,
    description: profile.bio || `${profile.fullName} adlı üyenin SohbeteGir.com profili.`,
  });
}

export default async function PublicProfilePage({ params }: Props) {
  const { username } = await params;
  const profile = await getPublicProfile(username);

  if (!profile) notFound();

  const viewer = await getCurrentUser();

  const [photos, activeStatus, likeCount, viewerLike] = await Promise.all([
    prisma.photo.findMany({
      where: { userId: profile.userId, kind: "GALLERY", status: "APPROVED" },
      orderBy: { sortOrder: "asc" },
    }),
    prisma.photo.findFirst({
      where: { userId: profile.userId, kind: "STATUS", status: "APPROVED", expiresAt: { gt: new Date() } },
      orderBy: { createdAt: "desc" },
    }),
    prisma.like.count({ where: { toUserId: profile.userId } }),
    viewer
      ? prisma.like.findUnique({
          where: { fromUserId_toUserId: { fromUserId: viewer.id, toUserId: profile.userId } },
        })
      : null,
  ]);

  const initials = profile.fullName
    .split(" ")
    .map((part) => part[0])
    .slice(0, 2)
    .join("")
    .toUpperCase();

  const isOwnProfile = viewer?.id === profile.userId;

  return (
    <div className="mx-auto max-w-2xl px-6 py-14">
      <JsonLd data={buildPersonSchema(profile)} />
      <div className="flex items-center gap-4">
        <div className="relative">
          {profile.avatarPhoto ? (
            <div className="h-16 w-16 overflow-hidden rounded-full">
              {/* eslint-disable-next-line @next/next/no-img-element -- yerel diskten servis edilen kullanıcı içeriği */}
              <img
                src={profile.avatarPhoto.thumbUrl}
                alt={profile.avatarPhoto.altText ?? profile.fullName}
                className="h-full w-full object-cover"
              />
            </div>
          ) : (
            <div className="flex h-16 w-16 items-center justify-center rounded-full bg-gradient-to-br from-accent to-accent-2 text-[20px] font-bold text-white">
              {initials}
            </div>
          )}
          {activeStatus && (
            <span className="absolute -bottom-1 -right-1 h-5 w-5 overflow-hidden rounded-full border-2 border-bg">
              {/* eslint-disable-next-line @next/next/no-img-element -- yerel diskten servis edilen kullanıcı içeriği */}
              <img src={activeStatus.thumbUrl} alt={activeStatus.altText ?? ""} className="h-full w-full object-cover" />
            </span>
          )}
        </div>
        <div className="flex-1">
          <h1 className="text-[24px]">{profile.fullName}</h1>
          {(profile.city || profile.age) && (
            <p className="text-[13.5px] text-text-muted">
              {[profile.city, profile.age ? `${profile.age} yaşında` : null].filter(Boolean).join(" · ")}
            </p>
          )}
        </div>
        {viewer && !isOwnProfile && (
          <div className="flex items-center gap-2">
            <LikeButton targetUserId={profile.userId} initiallyLiked={Boolean(viewerLike)} likeCount={likeCount} />
            <form action={startConversation.bind(null, profile.userId)}>
              <button
                type="submit"
                className="inline-flex items-center gap-2 rounded-full border border-border bg-surface px-5 py-2.5 text-[14px] font-semibold text-text-muted hover:border-accent hover:text-accent"
              >
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.8} strokeLinecap="round" strokeLinejoin="round">
                  <path d="M4 5h16a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H9l-5 4v-4H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1z" />
                </svg>
                Mesaj Gönder
              </button>
            </form>
          </div>
        )}
      </div>

      {profile.bio && <p className="mt-6 text-[14.5px] leading-relaxed text-text">{profile.bio}</p>}

      <div className="mt-8 grid grid-cols-2 gap-4">
        {profile.cinemaTaste && (
          <div className="rounded-2xl border border-border bg-surface p-4">
            <div className="text-[12px] font-semibold text-text-muted">Sinema Zevki</div>
            <div className="mt-1 text-[14px]">{profile.cinemaTaste}</div>
          </div>
        )}
        {profile.musicTaste && (
          <div className="rounded-2xl border border-border bg-surface p-4">
            <div className="text-[12px] font-semibold text-text-muted">Müzik Zevki</div>
            <div className="mt-1 text-[14px]">{profile.musicTaste}</div>
          </div>
        )}
        {profile.hobbies && (
          <div className="col-span-2 rounded-2xl border border-border bg-surface p-4">
            <div className="text-[12px] font-semibold text-text-muted">Hobiler</div>
            <div className="mt-1 text-[14px]">{profile.hobbies}</div>
          </div>
        )}
      </div>

      {photos.length > 0 && (
        <div className="mt-8">
          <h2 className="mb-3 text-[16px] font-bold">Galeri</h2>
          <PhotoGallery photos={photos} />
        </div>
      )}
    </div>
  );
}
