import Image from "next/image";
import Link from "next/link";
import prisma from "@/server/db/prisma";
import type { Project } from "@/types/models";

// TODO: Set revalidate to 600 (10 minutes) before deploying for ISR
// export const revalidate = 3600;
export const dynamic = "force-dynamic";

export async function generateMetadata() {
  const seo = await prisma.seometadata.findFirst({
    where: { pageType: "PROJECT" },
  });
  return {
    title: seo?.title || "Projects - Nitescape",
    description: seo?.metaDescription || "Explore our projects at Nitescape.",
  };
}

async function getProjects(): Promise<Project[]> {
  const dbProjects = await prisma.project.findMany();
  return dbProjects.map((p) => {
    let galleryImages: string[] = [];
    if (Array.isArray(p.galleryImages)) {
      galleryImages = p.galleryImages as string[];
    } else if (typeof p.galleryImages === "string") {
      try {
        const parsed = JSON.parse(p.galleryImages);
        if (Array.isArray(parsed)) {
          galleryImages = parsed;
        }
      } catch {
        galleryImages = [];
      }
    }
    return {
      id: p.id,
      name: p.name,
      description: p.description,
      shortDescription: (p as any).shortDescription || null,
      coverImage: p.coverImage ?? null,
      galleryImages,
    };
  });
}

function ProjectsClient({ projects }: { projects: Project[] }) {
  return (
    <section id="projects-section" className="relative min-h-screen py-24 overflow-hidden bg-[#030f18]">
      {/* Gradient border that fades from left to right */}
      <div className="absolute top-0 left-0 w-[85%] h-[1px] bg-gradient-to-r from-[#B87333] to-transparent" />
      {/* Background Elements */}
      <div className="absolute inset-0">
        <div className="absolute inset-0 opacity-5"></div>
      </div>
      {/* Floating Elements */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute top-1/4 left-1/4 w-64 h-64 bg-[#B87333]/10 rounded-full blur-3xl animate-float"></div>
        <div className="absolute bottom-1/4 right-1/4 w-96 h-96 bg-[#B87333]/10 rounded-full blur-3xl animate-float-delayed"></div>
      </div>
      <div className="container mx-auto px-4 relative z-10">
        {/* Section Header */}
        <div className="text-center mb-16">
          <h2 className="text-4xl md:text-5xl font-bold text-white mb-4">Our Projects</h2>
          <div className="w-20 h-1 bg-gradient-to-r from-[#B87333] to-[#ff914d] mx-auto rounded-full mb-6" />
          <p className="mt-2 text-gray-300 text-lg max-w-2xl mx-auto">
            Discover our portfolio of innovative lighting solutions and creative designs.
          </p>
        </div>
        {/* Projects Grid */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-8">
          {projects.map((project) => (
            <div
              key={project.id}
              className="group relative rounded-md border border-[#B87333]/30 shadow-md bg-[#020c13] overflow-hidden transform transition-all duration-300 hover:border-[#B87333] hover:shadow-lg"
            >
              <div className="relative aspect-[4/3]">
                {project.coverImage && (
                  <Image
                    src={project.coverImage.replace("/uploads/", "/api/uploads/")}
                    alt={project.name}
                    fill
                    className="object-cover transition-transform duration-300 group-hover:scale-105"
                    quality={85}
                  />
                )}
                <div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent flex flex-col justify-end p-6">
                  <h3 className="text-2xl font-bold text-white mb-2">{project.name}</h3>
                  <p className="text-gray-200 text-sm mb-4">
                    {project.shortDescription || project.description}
                  </p>
                  <Link
                    href={`/projects/${project.id}`}
                    className="inline-flex items-center text-[#B87333] hover:text-[#A05A2C] transition-colors focus:outline-none focus:underline"
                  >
                    View Project
                    <svg
                      className="w-5 h-5 ml-2 transform group-hover:translate-x-1 transition-transform"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth={2}
                        d="M17 8l4 4m0 0l-4 4m4-4H3"
                      />
                    </svg>
                  </Link>
                </div>
              </div>
            </div>
          ))}
        </div>
        {/* Back to Home Button */}
        <div className="text-center mt-16">
          <Link
            href="/"
            className="inline-flex items-center px-8 py-4 rounded-full bg-[#B87333] text-white font-semibold hover:bg-[#A05A2C] hover:shadow-lg hover:scale-105 transition-all duration-300 focus:outline-none focus:ring-2 focus:ring-[#B87333] focus:ring-offset-2 focus:ring-offset-[#030f18]"
          >
            <svg
              className="w-5 h-5 mr-2 transform group-hover:-translate-x-1 transition-transform"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M7 16l-4-4m0 0l4-4m-4 4h18"
              />
            </svg>
            Back to Home
          </Link>
        </div>
      </div>
    </section>
  );
}

export default async function Projects() {
  const projects = await getProjects();
  return <ProjectsClient projects={projects} />;
}
