"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import Image from "next/image";
import Link from "next/link";
import { ExternalLink, Filter, ArrowRight, Layers } from "lucide-react";
import { stripHtml, getDirectDriveLink } from "@/lib/text";

export default function ProjectGrid({ initialProjects, categories }: { initialProjects: any[], categories: string[] }) {
    const [filter, setFilter] = useState("Tous");
    const [currentPage, setCurrentPage] = useState(1);
    const itemsPerPage = 6;

    const filtered = filter === "Tous"
        ? initialProjects
        : initialProjects.filter(p => p.category?.name === filter);

    // Pagination logic
    const totalPages = Math.ceil(filtered.length / itemsPerPage);
    const startIndex = (currentPage - 1) * itemsPerPage;
    const paginatedProjects = filtered.slice(startIndex, startIndex + itemsPerPage);

    // Reset page when filter changes
    const handleFilterChange = (newFilter: string) => {
        setFilter(newFilter);
        setCurrentPage(1);
    };

    return (
        <>
            {/* Filters Section */}
            <div style={{ marginBottom: "5rem" }}>
                <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: "1.5rem" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: "0.75rem", color: "var(--muted-foreground)", fontWeight: 800, fontSize: "0.85rem", textTransform: "uppercase", letterSpacing: "0.1em" }}>
                        <Filter size={18} className="text-primary" /> Filtrer les réalisations
                    </div>
                    <div style={{ display: "flex", flexWrap: "wrap", justifyContent: "center", gap: "0.75rem" }}>
                        {categories.map(cat => (
                            <button key={cat} onClick={() => handleFilterChange(cat)}
                                style={{
                                    padding: "0.75rem 2rem",
                                    borderRadius: "var(--radius-full)",
                                    fontSize: "0.95rem",
                                    fontWeight: 700,
                                    transition: "all 0.4s cubic-bezier(0.4, 0, 0.2, 1)",
                                    cursor: "pointer",
                                    border: filter === cat ? "1.5px solid var(--primary)" : "1.5px solid var(--border)",
                                    background: filter === cat ? "var(--primary)" : "transparent",
                                    color: filter === cat ? "white" : "var(--foreground)",
                                    boxShadow: filter === cat ? "0 10px 20px -5px rgba(99, 102, 241, 0.3)" : "none",
                                }}>
                                {cat}
                            </button>
                        ))}
                    </div>
                </div>
            </div>

            {/* Empty State */}
            {filtered.length === 0 && (
                <div style={{ textAlign: "center", padding: "8rem 2rem", background: "var(--muted)", borderRadius: "var(--radius-lg)", border: "1px dashed var(--border)" }}>
                    <Layers size={48} className="text-muted-foreground" style={{ marginBottom: "1.5rem", opacity: 0.5 }} />
                    <h3 style={{ fontSize: "1.5rem", marginBottom: "0.5rem" }}>Aucun projet trouvé</h3>
                    <p style={{ color: "var(--muted-foreground)" }}>Essayez une autre catégorie ou revenez plus tard.</p>
                </div>
            )}

            {/* Grid display with animation */}
            <motion.div layout style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(340px, 1fr))", gap: "3rem" }}>
                <AnimatePresence mode="popLayout">
                    {paginatedProjects.map((project, i) => (
                        <motion.div key={project.id} layout initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, scale: 0.95 }} transition={{ duration: 0.5, delay: i * 0.05 }} className="card project-card"
                            style={{ overflow: "hidden", display: "flex", flexDirection: "column", height: "100%", padding: 0 }}>

                            {/* Enhanced Image Container */}
                            <div style={{ position: "relative", height: "18rem", overflow: "hidden" }}>
                                <Image src={getDirectDriveLink(project.image) || "https://images.unsplash.com/photo-1518770660439-4636190af475?auto=format&fit=crop&q=80&w=800"} alt={project.title} fill style={{ objectFit: "cover", transition: "transform 0.8s cubic-bezier(0.4, 0, 0.2, 1)" }} className="card-img" />
                                <div style={{ position: "absolute", inset: 0, background: "linear-gradient(to top, rgba(0,0,0,0.6) 0%, transparent 60%)", zIndex: 1 }} />

                                <div style={{ position: "absolute", top: "1.5rem", left: "1.5rem", zIndex: 10 }}>
                                    <span className="badge badge-primary" style={{ backdropFilter: "blur(8px)", background: "rgba(99, 102, 241, 0.9)", color: "white" }}>{project.category?.name || "Ingénierie"}</span>
                                </div>

                                {project.status === "En cours" && (
                                    <div style={{ position: "absolute", bottom: "1.5rem", left: "1.5rem", zIndex: 10, display: "flex", alignItems: "center", gap: "0.5rem", padding: "0.5rem 1rem", background: "rgba(245, 158, 11, 0.9)", backdropFilter: "blur(8px)", color: "white", borderRadius: "10px", fontSize: "0.8rem", fontWeight: 800 }}>
                                        <div className="pulse-dot" /> EN COURS
                                    </div>
                                )}
                            </div>

                            {/* Card Content with better typography */}
                            <div style={{ padding: "2.5rem", flex: 1, display: "flex", flexDirection: "column" }}>
                                <h3 style={{ fontSize: "1.6rem", marginBottom: "1.25rem", fontWeight: 800 }}>{project.title}</h3>
                                <p style={{ color: "var(--muted-foreground)", fontSize: "1rem", lineHeight: 1.8, flex: 1, marginBottom: "2.5rem" }}>
                                    {stripHtml(project.description).slice(0, 150)}...
                                </p>

                                <div style={{ display: "flex", flexWrap: "wrap", gap: "0.6rem", marginBottom: "2.5rem" }}>
                                    {project.technologies.slice(0, 4).map((t: string) => (
                                        <span key={t} style={{ padding: "0.4rem 1rem", background: "var(--primary-light)", borderRadius: "8px", fontSize: "0.75rem", fontWeight: 800, color: "var(--primary)", letterSpacing: "0.02em" }}>{t}</span>
                                    ))}
                                </div>

                                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", paddingTop: "2rem", borderTop: "1px solid var(--border)" }}>
                                    <Link href={`/projects/${project.id}`} className="btn-link" style={{ fontWeight: 800, fontSize: "0.9rem", color: "var(--primary)", display: "flex", alignItems: "center", gap: "0.6rem" }}>
                                        DÉTAILS DU PROJET <ArrowRight size={18} />
                                    </Link>
                                    <Link href={`/projects/${project.id}`} title="Voir les détails" style={{ width: 44, height: 44, borderRadius: "50%", background: "var(--muted)", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--muted-foreground)", transition: "all 0.3s" }} className="icon-btn">
                                        <ExternalLink size={20} />
                                    </Link>
                                </div>
                            </div>
                        </motion.div>
                    ))}
                </AnimatePresence>
            </motion.div>

            {/* Pagination Controls */}
            {totalPages > 1 && (
                <div style={{ display: "flex", justifyContent: "center", alignItems: "center", gap: "0.75rem", marginTop: "6rem" }}>
                    <button disabled={currentPage === 1} onClick={() => setCurrentPage(prev => prev - 1)} className="btn btn-outline" style={{ padding: "0.75rem 1.25rem", opacity: currentPage === 1 ? 0.5 : 1 }}>
                        Précédent
                    </button>
                    <div style={{ display: "flex", gap: "0.5rem" }}>
                        {Array.from({ length: totalPages }, (_, i) => (
                            <button key={i + 1} onClick={() => setCurrentPage(i + 1)}
                                style={{
                                    width: "44px", height: "44px", borderRadius: "12px", border: "1px solid var(--border)",
                                    background: currentPage === i + 1 ? "var(--primary)" : "var(--card-bg)",
                                    color: currentPage === i + 1 ? "white" : "var(--foreground)",
                                    fontWeight: 700, cursor: "pointer", transition: "all 0.3s"
                                }}>
                                {i + 1}
                            </button>
                        ))}
                    </div>
                    <button disabled={currentPage === totalPages} onClick={() => setCurrentPage(prev => prev + 1)} className="btn btn-outline" style={{ padding: "0.75rem 1.25rem", opacity: currentPage === totalPages ? 0.5 : 1 }}>
                        Suivant
                    </button>
                </div>
            )}

            <style>{`
                .pulse-dot {
                    width: 8px;
                    height: 8px;
                    background: white;
                    border-radius: 50%;
                    animation: pulse 2s infinite;
                }
                @keyframes pulse {
                    0% { transform: scale(0.9); opacity: 0.5; box-shadow: 0 0 0 0 rgba(255,255,255,0.7); }
                    70% { transform: scale(1.1); opacity: 1; box-shadow: 0 0 0 10px rgba(255,255,255,0); }
                    100% { transform: scale(0.9); opacity: 0.5; }
                }
                .project-card { transition: all 0.5s ease; border: 1.5px solid var(--border); }
                .project-card:hover { border-color: var(--primary); transform: translateY(-10px); }
                .project-card:hover .card-img { transform: scale(1.1); }
                .icon-btn:hover { background: var(--primary) !important; color: white !important; }
                .btn-link { position: relative; }
                .btn-link::after { content: ''; position: absolute; bottom: -4px; left: 0; width: 0; height: 2px; background: var(--primary); transition: width 0.3s; }
                .btn-link:hover::after { width: 100%; }
            `}</style>
        </>
    );
}
