import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Image from "next/image";
import { getTranslations } from "next-intl/server";
import { ExternalLink, Github, ArrowLeft, ArrowRight } from "lucide-react";
import { Link } from "@/lib/i18n/navigation";
import { getProjectBySlug } from "@/lib/db/projects";
import { TiptapRenderer } from "@/components/writing/TiptapRenderer";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";

interface Props {
  params: Promise<{ locale: string; slug: string }>;
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  const project = await getProjectBySlug(slug);
  if (!project) return {};
  return {
    title: project.seoTitle ?? project.title,
    description: project.seoDesc ?? project.description ?? undefined,
  };
}

export const dynamic = "force-dynamic";

export default async function ProjectPage({ params }: Props) {
  const { locale, slug } = await params;
  const [project, t, tWork] = await Promise.all([
    getProjectBySlug(slug),
    getTranslations({ locale, namespace: "common" }),
    getTranslations({ locale, namespace: "work" }),
  ]);

  if (!project) notFound();

  const isRtl = locale === "fa";
  const BackArrow = isRtl ? ArrowRight : ArrowLeft;

  return (
    <article className="relative z-10 pt-24">
      <div className="mx-auto max-w-4xl px-6 py-4">
        <Link
          href="/work"
          className="inline-flex items-center gap-2 text-sm text-text-secondary hover:text-accent transition-colors"
        >
          <BackArrow size={14} />
          {t("back")}
        </Link>
      </div>

      {/* Cover */}
      {project.coverImage && (
        <div className="relative mb-12 h-64 w-full overflow-hidden md:h-96">
          <Image src={project.coverImage} alt={project.title} fill className="object-cover" priority />
          <div className="absolute inset-0 bg-linear-to-b from-transparent to-background/80" />
        </div>
      )}

      <div className="mx-auto max-w-4xl px-6 pb-16">
        {/* Header */}
        <header className="mb-10">
          <Badge variant="secondary" className="mb-4">{project.projectType}</Badge>
          <h1 className="mb-4 text-3xl font-bold text-text-primary md:text-4xl">{project.title}</h1>
          {project.description && (
            <p className="text-lg text-text-secondary leading-relaxed">{project.description}</p>
          )}

          {/* CTA buttons */}
          <div className="mt-6 flex flex-wrap gap-3">
            {project.liveUrl && (
              <Button asChild>
                <a href={project.liveUrl} target="_blank" rel="noopener noreferrer">
                  <ExternalLink size={15} /> {t("live_demo")}
                </a>
              </Button>
            )}
            {project.githubUrl && (
              <Button asChild variant="secondary">
                <a href={project.githubUrl} target="_blank" rel="noopener noreferrer">
                  <Github size={15} /> {t("source_code")}
                </a>
              </Button>
            )}
          </div>
        </header>

        {/* Body */}
        {project.body && <TiptapRenderer html={project.body} />}

        {/* Tech stack + tools */}
        <div className="mt-10 grid gap-6 border-t border-border pt-8 sm:grid-cols-2">
          {project.techStack.length > 0 && (
            <div>
              <h3 className="mb-3 font-mono text-xs text-accent">// {tWork("tech_stack")}</h3>
              <div className="flex flex-wrap gap-2">
                {project.techStack.map((tech) => (
                  <span key={tech} className="rounded-full border border-border px-3 py-1 font-mono text-xs text-text-secondary">
                    {tech}
                  </span>
                ))}
              </div>
            </div>
          )}
          {project.toolsUsed.length > 0 && (
            <div>
              <h3 className="mb-3 font-mono text-xs text-accent">// {tWork("tools")}</h3>
              <div className="flex flex-wrap gap-2">
                {project.toolsUsed.map((tool) => (
                  <span key={tool} className="rounded-full border border-border px-3 py-1 font-mono text-xs text-text-secondary">
                    {tool}
                  </span>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Gallery */}
        {project.gallery.length > 0 && (
          <div className="mt-12">
            <h3 className="mb-4 font-mono text-xs text-accent">// gallery</h3>
            <div className="grid gap-4 sm:grid-cols-2">
              {project.gallery.map((imgUrl, i) => (
                <div key={i} className="relative aspect-video overflow-hidden rounded-lg border border-border">
                  <Image src={imgUrl} alt={`Gallery ${i + 1}`} fill className="object-cover" />
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    </article>
  );
}
