import type { Metadata } from "next";
import Link from "next/link";
import { requireUser } from "@/lib/auth/dal";
import { prisma } from "@/lib/db";
import { ProfileForm } from "@/components/profile/ProfileForm";
import { PhotoGallery } from "@/components/profile/PhotoGallery";
import { GalleryUploadForm, StatusUploadForm } from "@/components/profile/UploadForm";

export const metadata: Metadata = {
  title: "Profilim",
  robots: { index: false, follow: false },
};

export default async function MyProfilePage() {
  const user = await requireUser();
  const [profile, photos, activeStatuses, statusArchive] = await Promise.all([
    prisma.profile.findUniqueOrThrow({ where: { userId: user.id }, include: { avatarPhoto: true } }),
    prisma.photo.findMany({
      where: { userId: user.id, kind: "GALLERY" },
      orderBy: { sortOrder: "asc" },
    }),
    prisma.photo.findMany({
      where: { userId: user.id, kind: "STATUS", expiresAt: { gt: new Date() } },
      orderBy: { createdAt: "desc" },
    }),
    prisma.photo.findMany({
      where: { userId: user.id, kind: "STATUS", status: "APPROVED" },
      orderBy: { createdAt: "desc" },
    }),
  ]);

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

  return (
    <div className="mx-auto max-w-2xl px-6 py-14">
      <div className="mb-8 flex items-center gap-4">
        {profile.avatarPhoto ? (
          <div className="h-16 w-16 shrink-0 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 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-accent to-accent-2 text-[20px] font-bold text-white">
            {initials}
          </div>
        )}
        <div>
          <h1 className="text-[28px]">Profilim</h1>
          <p className="mt-1 text-[13.5px] text-text-muted">
            Herkese açık profilin:{" "}
            <Link href={`/profil/${profile.username}`} className="font-semibold text-accent">
              sohbetegir.com/profil/{profile.username}
            </Link>
          </p>
        </div>
      </div>

      <section className="mb-10 rounded-2xl border border-border bg-surface p-6">
        <h2 className="mb-1 text-[16px] font-bold">Anlık Durum</h2>
        <p className="mb-4 text-[13px] text-text-muted">
          Aynı anda birden fazla durum paylaşabilirsin, her biri 24 saat sonra otomatik kalkar. Yayınlanmadan önce
          admin onayından geçer. İstersen YouTube bağlantısıyla müzik, ya da bir üyeyi etiket olarak ekleyebilirsin.
        </p>
        {activeStatuses.length > 0 && (
          <div className="mb-4 flex flex-wrap gap-3">
            {activeStatuses.map((status) => (
              <div key={status.id} className="flex items-center gap-2.5 rounded-xl border border-border p-2 pr-3">
                {/* eslint-disable-next-line @next/next/no-img-element -- yerel diskten servis edilen kullanıcı içeriği */}
                <img src={status.thumbUrl} alt={status.altText ?? ""} className="h-12 w-12 rounded-lg object-cover" />
                <div>
                  <span className="block text-[11.5px] text-text-muted">
                    {status.status === "APPROVED" ? "Şu an yayında" : "Onay bekleniyor"}
                  </span>
                  {status.youtubeUrl && (
                    <span className="block text-[11px] font-semibold text-accent">
                      🎵 {status.youtubeTitle ?? "Müzik eklendi"}
                    </span>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
        <StatusUploadForm />
      </section>

      <section className="mb-10 rounded-2xl border border-border bg-surface p-6">
        <h2 className="mb-1 text-[16px] font-bold">Durum Arşivi</h2>
        <p className="mb-4 text-[13px] text-text-muted">Daha önce paylaştığın tüm durumlar burada saklanır.</p>
        {statusArchive.length === 0 ? (
          <p className="text-[13px] text-text-muted">Henüz durum paylaşmadın.</p>
        ) : (
          <div className="grid grid-cols-4 gap-3 sm:grid-cols-6">
            {statusArchive.map((status) => {
              const isActive = status.expiresAt !== null && status.expiresAt > new Date();
              return (
                <div key={status.id} className="group relative aspect-square overflow-hidden rounded-xl border border-border">
                  {/* eslint-disable-next-line @next/next/no-img-element -- yerel diskten servis edilen kullanıcı içeriği */}
                  <img src={status.thumbUrl} alt={status.altText ?? ""} className="h-full w-full object-cover" />
                  {isActive && (
                    <span className="absolute left-1.5 top-1.5 h-2 w-2 rounded-full bg-green-500" title="Şu an aktif" />
                  )}
                  {status.youtubeUrl && (
                    <span
                      className="absolute bottom-1.5 right-1.5 text-[13px] drop-shadow"
                      title={status.youtubeTitle ?? "Müzik eklendi"}
                    >
                      🎵
                    </span>
                  )}
                  <span className="absolute inset-x-0 bottom-0 bg-black/50 px-1.5 py-1 text-[9.5px] text-white">
                    {status.createdAt.toLocaleDateString("tr-TR")}
                  </span>
                </div>
              );
            })}
          </div>
        )}
      </section>

      <section className="mb-10 rounded-2xl border border-border bg-surface p-6">
        <h2 className="mb-1 text-[16px] font-bold">Fotoğraf Galerisi</h2>
        <p className="mb-4 text-[13px] text-text-muted">
          Yüklediğin fotoğraflar admin onayından sonra herkese görünür. Onaylı bir fotoğrafın üzerine gelip profil
          fotoğrafın yapabilirsin.
        </p>
        <div className="mb-4">
          <GalleryUploadForm />
        </div>
        <PhotoGallery photos={photos} editable avatarPhotoId={profile.avatarPhotoId} />
      </section>

      <ProfileForm profile={profile} />
    </div>
  );
}
