import Image from "next/image";
export const revalidate = 5;
import { stripHtml, getDirectDriveLink, getYouTubeEmbedUrl } from "@/lib/text";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, ExternalLink, Youtube, Github, Calendar, Tag } from "lucide-react";
import prisma from "@/lib/db";

import { Metadata } from "next";

type ProjectData = {
    id: string;
    title: string;
    description: string;
    image?: string | null;
    videoUrl?: string | null;
    repoUrl?: string | null;
    liveUrl?: string | null;
    technologies: string[];
    status: string;
    featured: boolean;
    createdAt: Date;
    category?: { name: string } | null;
};

export async function generateMetadata({ params }: { params: Promise<{ id: string }> }): Promise<Metadata> {
    const { id } = await params;
    const project = await prisma.project.findUnique({ where: { id } });
    if (!project) return { title: "Projet non trouvé" };
    const cleanDesc = stripHtml(project.description).slice(0, 160);
    return {
        title: `${project.title} | Sergio Hounkpessode`,
        description: cleanDesc,
        openGraph: {
            title: project.title,
            description: cleanDesc,
            images: project.image ? [getDirectDriveLink(project.image)] : [],
        }
    };
}

export default async function ProjectDetailPage({ params }: { params: Promise<{ id: string }> }) {
    const { id } = await params;

    const project = await prisma.project.findUnique({
        where: { id },
        include: { category: true },
    }) as ProjectData | null;

    if (!project) {
        notFound();
    }

    const statusColor = project.status === "Terminé"
        ? { bg: "rgba(34,197,94,0.1)", text: "#16a34a" }
        : { bg: "rgba(245,158,11,0.1)", text: "#d97706" };

    return (
        <div style={{ paddingTop: "8rem", paddingBottom: "6rem" }}>
            <div className="container" style={{ maxWidth: "72rem" }}>
                {/* Back */}
                <Link href="/projects" className="back-link" style={{ display: "inline-flex", alignItems: "center", gap: "0.75rem", color: "var(--primary)", fontWeight: 800, marginBottom: "3rem", fontSize: "0.95rem", textDecoration: "none" }}>
                    <ArrowLeft size={20} /> RETOUR AUX PROJETS
                </Link>

                {/* Hero Image */}
                <div className="hero-img-container" style={{ position: "relative", aspectRatio: "16/7", borderRadius: "1.75rem", overflow: "hidden", boxShadow: "0 24px 64px rgba(0,0,0,0.15)", marginBottom: "3rem", background: "#f1f5f9", transition: "all 0.4s ease" }}>
                    {project.image ? (
                        <Image src={getDirectDriveLink(project.image)} alt={project.title} fill style={{ objectFit: "cover" }} />
                    ) : (
                        <div style={{ width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--muted-foreground)" }}>Image non disponible</div>
                    )}
                    <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to bottom, transparent 60%, rgba(0,0,0,0.5))" }} />
                    <div style={{ position: "absolute", bottom: "2rem", left: "2rem", display: "flex", gap: "0.75rem", flexWrap: "wrap" }}>
                        <span style={{ padding: "0.4rem 1rem", background: "rgba(255,255,255,0.95)", borderRadius: 50, fontSize: "0.8rem", fontWeight: 900 }}>{project.category?.name || "Sans catégorie"}</span>
                        <span style={{ padding: "0.4rem 1rem", borderRadius: 50, fontSize: "0.8rem", fontWeight: 900, background: statusColor.bg, color: statusColor.text, border: `1px solid ${statusColor.text}40` }}>{project.status}</span>
                    </div>
                </div>

                <div style={{ display: "grid", gridTemplateColumns: "1fr", gap: "3rem" }} className="project-detail-grid">
                    {/* Main Content */}
                    <div>
                        <div style={{ marginBottom: "2.5rem" }}>
                            <div style={{ display: "flex", alignItems: "center", gap: "0.5rem", color: "var(--muted-foreground)", fontSize: "0.85rem", fontWeight: 600, marginBottom: "1rem" }}>
                                <Calendar size={14} /> {new Date(project.createdAt).toLocaleDateString("fr-FR", { year: "numeric", month: "long" })}
                            </div>
                            <h1 style={{ fontSize: "clamp(2.5rem, 5vw, 4.5rem)", fontWeight: 900, lineHeight: 1.1, letterSpacing: "-0.03em", marginBottom: "2.5rem" }}>
                                {project.title}
                            </h1>

                            <div
                                className="project-description rich-content"
                                style={{ lineHeight: 1.85, fontSize: "1.05rem", wordBreak: "break-word", overflowWrap: "anywhere" }}
                                dangerouslySetInnerHTML={{ __html: project.description }}
                            />

                            {/* YouTube Video Section */}
                            {project.videoUrl && getYouTubeEmbedUrl(project.videoUrl) && (
                                <div style={{ marginTop: "3rem", marginBottom: "3rem" }}>
                                    <h3 style={{ fontSize: "1.2rem", fontWeight: 900, marginBottom: "1.25rem", color: "#0f172a" }}>Vidéo de démonstration</h3>
                                    <div style={{ position: "relative", paddingBottom: "56.25%", height: 0, overflow: "hidden", borderRadius: "1.25rem", boxShadow: "0 10px 30px rgba(0,0,0,0.1)", background: "#000" }}>
                                        <iframe
                                            src={getYouTubeEmbedUrl(project.videoUrl)!}
                                            style={{ position: "absolute", top: 0, left: 0, width: "100%", height: "100%", border: "none" }}
                                            allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                                            allowFullScreen
                                            title={`Vidéo de ${project.title}`}
                                        />
                                    </div>
                                </div>
                            )}
                        </div>

                        {/* Tech Stack */}
                        <div style={{ borderTop: "1px solid var(--border)", paddingTop: "2rem" }}>
                            <h3 style={{ fontSize: "0.8rem", fontWeight: 800, textTransform: "uppercase", letterSpacing: "0.1em", color: "var(--muted-foreground)", marginBottom: "1rem", display: "flex", alignItems: "center", gap: "0.5rem" }}>
                                <Tag size={14} /> Technologies utilisées
                            </h3>
                            <div style={{ display: "flex", flexWrap: "wrap", gap: "0.6rem" }}>
                                {project.technologies.map(tech => (
                                    <span key={tech} style={{ padding: "0.5rem 1.1rem", background: "var(--secondary)", border: "1px solid var(--border)", borderRadius: "0.6rem", fontSize: "0.82rem", fontWeight: 800, textTransform: "uppercase", letterSpacing: "0.05em" }}>{tech}</span>
                                ))}
                            </div>
                        </div>
                    </div>

                    {/* Sidebar */}
                    <div style={{ display: "flex", flexDirection: "column", gap: "1.5rem" }}>
                        <div style={{ background: "var(--card)", border: "1px solid var(--border)", borderRadius: "1.25rem", padding: "1.75rem" }}>
                            <h3 style={{ fontSize: "1rem", fontWeight: 900, marginBottom: "1.25rem" }}>Détails du projet</h3>
                            <div style={{ display: "flex", flexDirection: "column", gap: "1rem" }}>
                                {[
                                    { label: "Statut", value: <span style={{ padding: "0.3rem 0.85rem", borderRadius: 50, fontSize: "0.8rem", fontWeight: 900, background: statusColor.bg, color: statusColor.text }}>{project.status}</span> },
                                    { label: "Catégorie", value: project.category?.name || "—" },
                                    { label: "En vedette", value: project.featured ? "⭐ Oui" : "Non" },
                                ].map(({ label, value }) => (
                                    <div key={label} style={{ display: "flex", justifyContent: "space-between", alignItems: "center", paddingBottom: "0.875rem", borderBottom: "1px solid var(--border)" }}>
                                        <span style={{ fontSize: "0.85rem", fontWeight: 700, color: "var(--muted-foreground)" }}>{label}</span>
                                        <span style={{ fontWeight: 800, fontSize: "0.9rem" }}>{value}</span>
                                    </div>
                                ))}
                            </div>
                        </div>

                        <div style={{ background: "var(--card)", border: "1px solid var(--border)", borderRadius: "1.25rem", padding: "1.75rem" }}>
                            <h3 style={{ fontSize: "1rem", fontWeight: 900, marginBottom: "1.25rem" }}>Liens</h3>
                            <div style={{ display: "flex", flexDirection: "column", gap: "0.75rem" }}>
                                {project.liveUrl && (
                                    <a href={project.liveUrl} target="_blank" rel="noopener noreferrer"
                                        style={{ display: "flex", alignItems: "center", gap: "0.75rem", padding: "0.875rem 1rem", background: "var(--primary)", color: "#fff", borderRadius: "0.875rem", fontWeight: 800, fontSize: "0.9rem" }}>
                                        <ExternalLink size={18} /> Voir la démonstration
                                    </a>
                                )}
                                {project.repoUrl && (
                                    <a href={project.repoUrl} target="_blank" rel="noopener noreferrer"
                                        style={{ display: "flex", alignItems: "center", gap: "0.75rem", padding: "0.875rem 1rem", background: "var(--secondary)", color: "var(--foreground)", border: "1px solid var(--border)", borderRadius: "0.875rem", fontWeight: 800, fontSize: "0.9rem" }}>
                                        <Github size={18} /> Code source (GitHub)
                                    </a>
                                )}
                                {project.videoUrl && (
                                    <a href={project.videoUrl} target="_blank" rel="noopener noreferrer"
                                        style={{ display: "flex", alignItems: "center", gap: "0.75rem", padding: "0.875rem 1rem", background: "rgba(239,68,68,0.08)", color: "#dc2626", border: "1px solid rgba(239,68,68,0.2)", borderRadius: "0.875rem", fontWeight: 800, fontSize: "0.9rem" }}>
                                        <Youtube size={18} /> Voir la vidéo YouTube
                                    </a>
                                )}
                                {!project.liveUrl && !project.repoUrl && !project.videoUrl && (
                                    <p style={{ color: "var(--muted-foreground)", fontSize: "0.875rem", textAlign: "center", padding: "1rem" }}>Aucun lien disponible.</p>
                                )}
                            </div>
                        </div>

                        <div style={{ background: "linear-gradient(135deg, var(--primary), #60a5fa)", borderRadius: "1.25rem", padding: "1.75rem", color: "#fff", textAlign: "center" }}>
                            <p style={{ fontWeight: 900, fontSize: "1.05rem", marginBottom: "0.5rem" }}>Intéressé par ce projet ?</p>
                            <p style={{ opacity: 0.85, fontSize: "0.875rem", marginBottom: "1.25rem" }}>Contactez-moi pour acquérir les sources ou démarrer un projet similaire.</p>
                            <Link href="/contact" style={{ display: "block", padding: "0.75rem", background: "rgba(255,255,255,0.2)", color: "#fff", border: "2px solid rgba(255,255,255,0.4)", borderRadius: "0.75rem", fontWeight: 900, fontSize: "0.9rem" }}>
                                Me contacter
                            </Link>
                        </div>
                    </div>
                </div>
            </div>

            <style>{`
                .project-detail-grid { grid-template-columns: 1.4fr 0.6fr; }
                @media(max-width: 900px){
                  .project-detail-grid { grid-template-columns: 1fr !important; }
                  .hero-img-container { aspect-ratio: 16/9 !important; }
                }
            `}</style>
        </div>
    );
}
