import { prisma } from '@/lib/db';
import Header from '@/components/ui/header';
import Footer from '@/components/ui/footer';
import Image from 'next/image';
import Link from 'next/link';
import { Camera, Calendar, ArrowLeft, ChevronLeft, ChevronRight, Sparkles } from 'lucide-react';
import { BRAND } from '@/lib/white-label/constants';

export const dynamic = 'force-dynamic';

export const metadata = {
  title: `Past Photos — Tesa's Tantalizing Tease | ${BRAND.companyName}`,
  description: 'Browse the full archive of Tes\'s fashion looks, summer collections, and more.',
};

const PER_PAGE = 12;

export default async function ArchivePage({
  searchParams,
}: {
  searchParams: { page?: string; style?: string };
}) {
  const page = Math.max(1, parseInt(searchParams.page || '1', 10) || 1);
  const styleFilter = searchParams.style || '';

  const where: any = { isPrivate: false };
  if (styleFilter) {
    where.style = styleFilter;
  }

  const [photos, total] = await Promise.all([
    prisma.tesFashion.findMany({
      where,
      orderBy: { date: 'desc' },
      skip: (page - 1) * PER_PAGE,
      take: PER_PAGE,
    }),
    prisma.tesFashion.count({ where }),
  ]);

  const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));

  // Get all unique styles for filter chips
  const allStyles = await prisma.tesFashion.findMany({
    where: { isPrivate: false },
    select: { style: true },
    distinct: ['style'],
    orderBy: { style: 'asc' },
  });
  const uniqueStyles = allStyles.map((s: any) => s.style).filter(Boolean) as string[];

  function buildUrl(p: number, s?: string) {
    const params = new URLSearchParams();
    if (p > 1) params.set('page', String(p));
    if (s) params.set('style', s);
    const qs = params.toString();
    return `/tesa/gallery/archive${qs ? '?' + qs : ''}`;
  }

  return (
    <main className="min-h-screen bg-brand-bg">
      <Header />

      <div className="pt-28 pb-20 px-4">
        <div className="max-w-6xl mx-auto">
          {/* Back Link */}
          <Link
            href="/tesa/gallery"
            className="inline-flex items-center gap-2 text-gray-400 hover:text-brand transition-colors mb-8"
          >
            <ArrowLeft className="w-4 h-4" />
            Back to Gallery
          </Link>

          {/* Header */}
          <div className="text-center mb-10">
            <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-gradient-to-r from-brand-secondary/20 to-pink-500/20 border border-brand-secondary/30 mb-6">
              <Camera className="w-4 h-4 text-pink-400" />
              <span className="text-sm text-pink-300">Past Photos</span>
            </div>
            <h1 className="text-3xl md:text-4xl font-bold text-white mb-3">
              The Full Archive
            </h1>
            <p className="text-lg text-gray-400 max-w-xl mx-auto">
              Every look Tes has ever served. Scroll back through the drip.
            </p>
            <p className="text-sm text-gray-500 mt-3">
              {total} photo{total !== 1 ? 's' : ''} total
            </p>
          </div>

          {/* Style Filter Chips */}
          {uniqueStyles.length > 1 && (
            <div className="flex flex-wrap items-center justify-center gap-2 mb-10">
              <Link
                href={buildUrl(1)}
                className={`px-4 py-1.5 rounded-full text-sm font-medium transition-all ${
                  !styleFilter
                    ? 'bg-brand text-white'
                    : 'bg-white/5 text-gray-400 hover:text-white hover:bg-white/10 border border-white/10'
                }`}
              >
                All
              </Link>
              {uniqueStyles.map((style) => (
                <Link
                  key={style}
                  href={buildUrl(1, style)}
                  className={`px-4 py-1.5 rounded-full text-sm font-medium transition-all ${
                    styleFilter === style
                      ? 'bg-brand text-white'
                      : 'bg-white/5 text-gray-400 hover:text-white hover:bg-white/10 border border-white/10'
                  }`}
                >
                  {style}
                </Link>
              ))}
            </div>
          )}

          {/* Photo Grid */}
          {photos.length > 0 ? (
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4 mb-12">
              {photos.map((photo: any) => (
                <div
                  key={photo.id}
                  className="glass-card p-1.5 rounded-xl bg-black/30 group cursor-pointer hover:bg-black/50 transition-all"
                >
                  <div className="relative aspect-[3/4] rounded-lg overflow-hidden bg-gradient-to-br from-brand-secondary/5 to-pink-500/5">
                    <Image
                      src={photo.imageUrl ?? ''}
                      alt={photo.description ?? 'Fashion photo'}
                      fill
                      className="object-cover transition-transform group-hover:scale-105"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity" />
                    <div className="absolute bottom-0 left-0 right-0 p-3 opacity-0 group-hover:opacity-100 transition-opacity">
                      <span className="text-xs text-pink-300 font-medium capitalize">
                        {(photo.style ?? 'fashion').replace(/-/g, ' ')}
                      </span>
                      <p className="text-white text-sm line-clamp-2 mt-1">
                        {photo.description ?? ''}
                      </p>
                      <div className="flex items-center gap-1 mt-2 text-gray-400">
                        <Calendar className="w-3 h-3" />
                        <span className="text-xs">
                          {new Date(photo.date).toLocaleDateString('en-US', {
                            month: 'short',
                            day: 'numeric',
                            year: 'numeric',
                          })}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ) : (
            <div className="glass-card p-12 rounded-2xl bg-black/50 text-center mb-12">
              <Camera className="w-12 h-12 text-gray-600 mx-auto mb-3" />
              <h3 className="text-lg font-semibold text-white mb-2">No Photos Found</h3>
              <p className="text-gray-400">
                {styleFilter
                  ? `No photos with the "${styleFilter}" style yet.`
                  : 'No photos in the archive yet. Check back soon!'}
              </p>
              {styleFilter && (
                <Link
                  href={buildUrl(1)}
                  className="inline-block mt-4 px-5 py-2 rounded-lg bg-brand/20 text-brand hover:bg-brand/30 transition-colors text-sm"
                >
                  Clear Filter
                </Link>
              )}
            </div>
          )}

          {/* Pagination */}
          {totalPages > 1 && (
            <div className="flex items-center justify-center gap-3">
              {page > 1 ? (
                <Link
                  href={buildUrl(page - 1, styleFilter || undefined)}
                  className="flex items-center gap-1 px-4 py-2 rounded-lg bg-white/5 text-gray-300 hover:bg-white/10 hover:text-white transition-all border border-white/10"
                >
                  <ChevronLeft className="w-4 h-4" />
                  Prev
                </Link>
              ) : (
                <span className="flex items-center gap-1 px-4 py-2 rounded-lg bg-white/5 text-gray-600 border border-white/5 cursor-not-allowed">
                  <ChevronLeft className="w-4 h-4" />
                  Prev
                </span>
              )}

              <div className="flex items-center gap-1">
                {Array.from({ length: totalPages }, (_, i) => i + 1)
                  .filter((p) => p === 1 || p === totalPages || Math.abs(p - page) <= 1)
                  .reduce<(number | string)[]>((acc, p, i, arr) => {
                    if (i > 0 && (p - (arr[i - 1] as number)) > 1) acc.push('...');
                    acc.push(p);
                    return acc;
                  }, [])
                  .map((item, i) =>
                    typeof item === 'string' ? (
                      <span key={`dots-${i}`} className="px-2 text-gray-500">
                        …
                      </span>
                    ) : (
                      <Link
                        key={item}
                        href={buildUrl(item, styleFilter || undefined)}
                        className={`w-9 h-9 flex items-center justify-center rounded-lg text-sm font-medium transition-all ${
                          item === page
                            ? 'bg-brand text-white'
                            : 'bg-white/5 text-gray-400 hover:bg-white/10 hover:text-white border border-white/10'
                        }`}
                      >
                        {item}
                      </Link>
                    )
                  )}
              </div>

              {page < totalPages ? (
                <Link
                  href={buildUrl(page + 1, styleFilter || undefined)}
                  className="flex items-center gap-1 px-4 py-2 rounded-lg bg-white/5 text-gray-300 hover:bg-white/10 hover:text-white transition-all border border-white/10"
                >
                  Next
                  <ChevronRight className="w-4 h-4" />
                </Link>
              ) : (
                <span className="flex items-center gap-1 px-4 py-2 rounded-lg bg-white/5 text-gray-600 border border-white/5 cursor-not-allowed">
                  Next
                  <ChevronRight className="w-4 h-4" />
                </span>
              )}
            </div>
          )}
        </div>
      </div>

      <Footer />
    </main>
  );
}
