"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { AnimatedSection } from "@/shared/components/animated-section";
import { SectionHeading } from "@/shared/components/section-heading";
import { ProjectDetailModal } from "./project-detail-modal";
import {
  ExternalLink,
  GitFork,
  TrendingUp,
  Server,
  Smartphone,
  Globe,
  Layers,
} from "lucide-react";
import { useTranslations } from "next-intl";

export function ProjectsSection({ initialProjects }: { initialProjects?: any[] }) {
  const t = useTranslations("Projects");
  const [activeFilter, setActiveFilter] = useState("all");
  const [selectedProject, setSelectedProject] = useState<any | null>(null);

  // Use initialProjects from DB or fallback to empty array
  const projects = initialProjects || [];

  const filters = [
    { value: "all", label: t("filters.all"), icon: <Layers size={16} /> },
    { value: "Enterprise Backend", label: "Backend", icon: <Server size={16} /> },
    { value: "Frontend Development", label: "Frontend", icon: <Globe size={16} /> },
    { value: "Mobile Development", label: "Mobile", icon: <Smartphone size={16} /> },
  ];

  const filteredProjects =
    activeFilter === "all"
      ? projects
      : projects.filter((p) => p.category === activeFilter);

  return (
    <section id="projects" className="section-padding relative">
      <div className="max-w-6xl mx-auto px-6">
        <AnimatedSection>
          <SectionHeading
            title={t("title")}
            subtitle={t("subtitle")}
          />
        </AnimatedSection>

        {/* Filter tabs */}
        <AnimatedSection delay={0.1}>
          <div className="flex flex-wrap items-center justify-center gap-2 mb-12">
            {filters.map((filter) => (
              <button
                key={filter.value}
                onClick={() => setActiveFilter(filter.value)}
                className={`inline-flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-300 ${activeFilter === filter.value
                    ? "bg-accent text-accent-foreground shadow-lg shadow-accent/25"
                    : "bg-muted/50 text-muted-foreground border border-border/50 hover:border-accent/30 hover:text-foreground"
                  }`}
              >
                {filter.icon}
                {filter.label}
              </button>
            ))}
          </div>
        </AnimatedSection>

        {/* Empty state */}
        {filteredProjects.length === 0 ? (
          <AnimatedSection delay={0.2}>
            <div className="flex flex-col items-center justify-center py-20 text-center">
              <div className="w-20 h-20 rounded-2xl bg-muted/50 border border-border/50 flex items-center justify-center mb-6">
                <Layers size={32} className="text-muted-foreground/40" />
              </div>
              <h3 className="text-lg font-bold mb-2">Belum ada project</h3>
              <p className="text-sm text-muted-foreground max-w-sm">
                Project sedang dalam persiapan. Nantikan case study yang akan datang!
              </p>
            </div>
          </AnimatedSection>
        ) : (
        <>
        {/* Projects grid */}
        <motion.div
          layout
          className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5"
        >
          <AnimatePresence mode="popLayout">
            {filteredProjects.map((project) => (
              <motion.div
                key={project.id}
                layout
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.9 }}
                transition={{ duration: 0.3 }}
              >
                <div 
                  className="project-card group relative h-full flex flex-col p-6 rounded-2xl bg-card border border-border/50 hover:border-accent/30 transition-all duration-500 cursor-pointer"
                  onClick={() => setSelectedProject(project)}
                >
                  {/* Category badge */}
                  <div className="flex items-center justify-between mb-4">
                    <span
                      className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[10px] font-mono font-semibold uppercase tracking-wider ${project.category === "Enterprise Backend"
                          ? "bg-blue-500/10 text-blue-500 dark:text-blue-400"
                          : project.category === "Frontend Development"
                            ? "bg-violet-500/10 text-violet-500 dark:text-violet-400"
                            : "bg-orange-500/10 text-orange-500 dark:text-orange-400"
                        }`}
                    >
                      {project.category === "Enterprise Backend" ? (
                        <Server size={12} />
                      ) : project.category === "Frontend Development" ? (
                        <Globe size={12} />
                      ) : (
                        <Smartphone size={12} />
                      )}
                      {project.category.replace(" Development", "").replace("Enterprise ", "")}
                    </span>
                    <div className="flex items-center gap-1.5">
                      {project.repoUrl && (
                        <a
                          href={project.repoUrl}
                          className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors"
                          aria-label="GitHub"
                        >
                          <GitFork size={14} />
                        </a>
                      )}
                      {project.liveUrl && (
                        <a
                          href={project.liveUrl}
                          className="p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors"
                          aria-label="Live demo"
                        >
                          <ExternalLink size={14} />
                        </a>
                      )}
                    </div>
                  </div>

                  {/* Image banner */}
                  {project.imageUrl && (
                    <div className="w-full h-40 mb-4 rounded-xl overflow-hidden bg-muted/20 relative">
                      <img 
                        src={project.imageUrl} 
                        alt={project.title}
                        className="w-full h-full object-cover group-hover:scale-110 transition-transform duration-700" 
                      />
                      <div className="absolute inset-0 bg-gradient-to-t from-card/40 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500" />
                    </div>
                  )}

                  {/* Title & description */}
                  <h3 className="text-lg font-bold mb-2 group-hover:text-accent transition-colors">
                    {project.title}
                  </h3>
                  <p className="text-sm text-muted-foreground leading-relaxed mb-4 flex-1">
                    {project.description}
                  </p>

                  {/* Metrics badge */}
                  {project.metrics && (
                    <div className="flex items-center gap-2 mb-4 px-3 py-2 rounded-lg bg-success/5 border border-success/10">
                      <TrendingUp size={14} className="text-success" />
                      <span className="text-xs font-mono font-medium text-success">
                        {project.metrics}
                      </span>
                    </div>
                  )}

                  {/* Tech Stack Badges */}
                  <div className="flex flex-wrap gap-1.5 mt-auto">
                    {project.techStack?.length > 0 ? (
                      project.techStack.map((tech: string) => (
                        <span
                          key={tech}
                          className="px-2 py-1 rounded-md text-[10px] font-mono bg-accent/10 text-accent border border-accent/20"
                        >
                          {tech}
                        </span>
                      ))
                    ) : (
                      (project.tags || [project.category.split(" ")[0]]).map((tag: string) => (
                        <span
                          key={tag}
                          className="px-2 py-1 rounded-md text-[10px] font-mono bg-muted/50 text-muted-foreground border border-border/30"
                        >
                          {tag}
                        </span>
                      ))
                    )}
                  </div>
                  
                  {/* Year */}
                  {project.year && (
                    <div className="absolute top-6 right-6 opacity-0 group-hover:opacity-100 transition-opacity">
                       <span className="px-2 py-1 rounded-lg bg-card/80 backdrop-blur-sm border border-border text-[10px] font-mono text-muted-foreground shadow-sm">
                         {project.year}
                       </span>
                    </div>
                  )}
                </div>
              </motion.div>
            ))}
          </AnimatePresence>
        </motion.div>
        
        {/* Detail Modal */}
        {selectedProject && (
          <ProjectDetailModal 
            project={selectedProject} 
            onClose={() => setSelectedProject(null)} 
          />
        )}
        </>
        )}
      </div>
    </section>
  );
}
