import { useState, useMemo } from "react";
import { Link } from "react-router-dom";
import { Server, Cloud, Shield, Network, ArrowLeft, Filter, X } from "lucide-react";
import { motion, AnimatePresence, type Variants } from "framer-motion";
import { useLanguage } from "@/contexts/LanguageContext";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import Navigation from "@/components/cv/Navigation";
import Footer from "@/components/cv/Footer";
import ProjectCard from "@/components/projects/ProjectCard";
import ProjectDetail from "@/components/projects/ProjectDetail";
import TechnologyFilter from "@/components/projects/TechnologyFilter";
import SeoMeta from "@/components/seo/SeoMeta";


// Import project mockup images (AVIF + WebP + JPG sets)
import {
  klepierreLandingZone,
  cloudMigration,
  kubernetesMonitoring,
  identityManagement,
  finopsOptimization,
  disasterRecovery,
  personalAzTrainer,
  pilotcrew as pilotCrewImage,
} from "@/assets/projects";
import type { ImageSet } from "@/components/ui/Picture";

// Import company logos
import klepierreLogo from "@/assets/companies/klepierre.jpg";
import devoteamLogo from "@/assets/companies/devoteam.svg";
import atosLogo from "@/assets/companies/atos.svg";
import absysCyborgLogo from "@/assets/companies/absyscyborg.svg";

export interface Project {
  id: string;
  icon: typeof Cloud;
  titleKey: string;
  descriptionKey: string;
  detailsKey: string;
  tags: string[];
  color: string;
  image: ImageSet;
  category: "cloud" | "devops" | "security";
  companyKey: string;
  companyLogo?: string;
  periodKey: string;
  experienceId: string; // ID to link to experience section
  isCurrent?: boolean;
  isPersonalProject?: boolean;
  externalUrl?: string;
}

const containerVariants: Variants = {
  hidden: { opacity: 0 },
  visible: {
    opacity: 1,
    transition: {
      staggerChildren: 0.1,
      delayChildren: 0.2,
    },
  },
};

const headerVariants: Variants = {
  hidden: { opacity: 0, y: -20 },
  visible: {
    opacity: 1,
    y: 0,
    transition: { duration: 0.5, ease: "easeOut" },
  },
};

const Projects = () => {
  const { t } = useLanguage();
  const [selectedTechnologies, setSelectedTechnologies] = useState<string[]>([]);
  const [selectedProject, setSelectedProject] = useState<Project | null>(null);

  const projects: Project[] = [
    {
      id: "klepierre-landing-zone",
      icon: Cloud,
      titleKey: "portfolio.project1.title",
      descriptionKey: "portfolio.project1.description",
      detailsKey: "projects.project1.details",
      tags: ["Azure", "Terraform", "Bicep", "Hub & Spoke", "vWAN", "Azure Policy", "Azure DevOps", "PowerShell", "Entra ID"],
      color: "from-blue-900 to-blue-600",
      image: klepierreLandingZone,
      category: "cloud",
      companyKey: "experience.job1.company",
      companyLogo: klepierreLogo,
      periodKey: "experience.job1.period",
      experienceId: "experience-klepierre",
      isCurrent: true,
    },
    {
      id: "hub-spoke-vwan",
      icon: Network,
      titleKey: "portfolio.project11.title",
      descriptionKey: "portfolio.project11.description",
      detailsKey: "projects.project11.details",
      tags: ["Azure Virtual WAN", "Hub & Spoke", "vWAN", "ExpressRoute", "Azure Firewall", "BGP", "Zero Trust", "Network Watcher", "Terraform"],
      color: "from-sky-600 to-blue-500",
      image: klepierreLandingZone,
      category: "cloud",
      companyKey: "experience.job1.company",
      companyLogo: klepierreLogo,
      periodKey: "experience.job1.period",
      experienceId: "experience-klepierre",
      isCurrent: true,
    },
    {
      id: "ai-concierge",
      icon: Cloud,
      titleKey: "portfolio.project2.title",
      descriptionKey: "portfolio.project2.description",
      detailsKey: "projects.project2.details",
      tags: ["Azure OpenAI", "LangGraph", "MCP", "RAG", "ServiceNow", "Container Apps", "pgvector", "Application Insights"],
      color: "from-violet-600 to-indigo-500",
      image: pilotCrewImage,
      category: "cloud",
      companyKey: "experience.job1.company",
      companyLogo: klepierreLogo,
      periodKey: "experience.job1.period",
      experienceId: "experience-klepierre",
      isCurrent: true,
    },
    {
      id: "governance-finops",
      icon: Shield,
      titleKey: "portfolio.project3.title",
      descriptionKey: "portfolio.project3.description",
      detailsKey: "projects.project3.details",
      tags: ["Azure Policy", "FinOps", "Wiz", "Trivy", "Reserved Instances", "Tagging", "Terraform", "Azure DevOps"],
      color: "from-emerald-500 to-green-500",
      image: finopsOptimization,
      category: "cloud",
      companyKey: "experience.job1.company",
      companyLogo: klepierreLogo,
      periodKey: "experience.job1.period",
      experienceId: "experience-klepierre",
      isCurrent: true,
    },
    {
      id: "cloud-migration",
      icon: Shield,
      titleKey: "portfolio.project4.title",
      descriptionKey: "portfolio.project4.description",
      detailsKey: "projects.project4.details",
      tags: ["Azure Migrate", "Entra ID", "NSG", "ExpressRoute"],
      color: "from-green-500 to-emerald-500",
      image: cloudMigration,
      category: "security",
      companyKey: "experience.job4.company",
      companyLogo: atosLogo,
      periodKey: "experience.job4.period",
      experienceId: "experience-atos",
    },
    {
      id: "kubernetes-monitoring",
      icon: Server,
      titleKey: "portfolio.project5.title",
      descriptionKey: "portfolio.project5.description",
      detailsKey: "projects.project5.details",
      tags: ["Kubernetes", "Prometheus", "Grafana", "Helm", "ArgoCD"],
      color: "from-cyan-500 to-blue-500",
      image: kubernetesMonitoring,
      category: "devops",
      companyKey: "experience.job4.company",
      companyLogo: atosLogo,
      periodKey: "experience.job4.period",
      experienceId: "experience-atos",
    },
    {
      id: "identity-management",
      icon: Shield,
      titleKey: "portfolio.project6.title",
      descriptionKey: "portfolio.project6.description",
      detailsKey: "projects.project6.details",
      tags: ["Entra ID", "SSO", "MFA", "RBAC", "Conditional Access"],
      color: "from-purple-500 to-pink-500",
      image: identityManagement,
      category: "security",
      companyKey: "experience.job2.company",
      companyLogo: devoteamLogo,
      periodKey: "experience.job2.period",
      experienceId: "experience-devoteam",
    },
    {
      id: "finops-optimization",
      icon: Cloud,
      titleKey: "portfolio.project7.title",
      descriptionKey: "portfolio.project7.description",
      detailsKey: "projects.project7.details",
      tags: ["Azure Cost Management", "AWS Cost Explorer", "FinOps", "Budgets"],
      color: "from-emerald-500 to-green-500",
      image: finopsOptimization,
      category: "cloud",
      companyKey: "experience.job5.company",
      companyLogo: absysCyborgLogo,
      periodKey: "experience.job5.period",
      experienceId: "experience-absyscyborg",
    },
    {
      id: "disaster-recovery",
      icon: Shield,
      titleKey: "portfolio.project8.title",
      descriptionKey: "portfolio.project8.description",
      detailsKey: "projects.project8.details",
      tags: ["Azure Site Recovery", "Backup", "Multi-Region", "RTO/RPO"],
      color: "from-amber-500 to-orange-500",
      image: disasterRecovery,
      category: "security",
      companyKey: "experience.job4.company",
      companyLogo: atosLogo,
      periodKey: "experience.job4.period",
      experienceId: "experience-atos",
    },
    {
      id: "pilotcrew",
      icon: Server,
      titleKey: "portfolio.project10.title",
      descriptionKey: "portfolio.project10.description",
      detailsKey: "projects.project10.details",
      tags: ["React", "Next.js", "TypeScript", "Supabase", "OpenAI", "Anthropic", "Stripe", "Tailwind CSS"],
      color: "from-violet-600 to-indigo-500",
      image: pilotCrewImage,
      category: "devops",
      companyKey: "projects.personalProject",
      periodKey: "projects.personalProjectPeriod",
      experienceId: "",
      isPersonalProject: true,
      externalUrl: "https://pilotcrew.io/",
    },
    {
      id: "personal-az-trainer",
      icon: Cloud,
      titleKey: "portfolio.project9.title",
      descriptionKey: "portfolio.project9.description",
      detailsKey: "projects.project9.details",
      tags: ["React", "TypeScript", "Azure", "Tailwind CSS", "Vite"],
      color: "from-blue-600 to-cyan-400",
      image: personalAzTrainer,
      category: "cloud",
      companyKey: "projects.personalProject",
      periodKey: "projects.personalProjectPeriod",
      experienceId: "",
      isPersonalProject: true,
      externalUrl: "https://personal-az-trainer.com/",
    },
  ];

  // Extract all unique technologies
  const allTechnologies = useMemo(() => {
    const techSet = new Set<string>();
    projects.forEach((project) => {
      project.tags.forEach((tag) => techSet.add(tag));
    });
    return Array.from(techSet).sort();
  }, []);

  // Filter projects based on selected technologies
  const filteredProjects = useMemo(() => {
    if (selectedTechnologies.length === 0) return projects;
    return projects.filter((project) =>
      selectedTechnologies.some((tech) => project.tags.includes(tech))
    );
  }, [selectedTechnologies, projects]);

  const toggleTechnology = (tech: string) => {
    setSelectedTechnologies((prev) =>
      prev.includes(tech)
        ? prev.filter((t) => t !== tech)
        : [...prev, tech]
    );
  };

  const clearFilters = () => {
    setSelectedTechnologies([]);
  };

  const ogTitle = "Projets Cloud, DevOps & AI Agentic · Curtys Accipe";
  const ogDescription = "Portfolio Cloud Azure & AI Agentic : Landing Zone Enterprise Scale, agents IA (LangGraph, MCP, RAG), FinOps. Filtrable par techno.";

  return (
    <div className="min-h-screen bg-background text-foreground">
      <SeoMeta
        title={ogTitle}
        description={ogDescription}
        path="/projects"
        ogImage={{
          title: "Projets Cloud, DevOps & AI Agentic",
          subtitle: "Landing Zone Enterprise Scale · Agents IA LangGraph/MCP/RAG · FinOps",
          tag: "projects · curtys-accipe.dev",
        }}
        pageType="CollectionPage"
        schemaName="Projets — Curtys Accipe"
        schemaDescription={ogDescription}
        extraJsonLd={[
          {
            "@context": "https://schema.org",
            "@type": "BreadcrumbList",
            "itemListElement": [
              { "@type": "ListItem", "position": 1, "name": "Accueil", "item": "https://curtys-accipe.dev/" },
              { "@type": "ListItem", "position": 2, "name": "Projets", "item": "https://curtys-accipe.dev/projects" },
            ],
          },
        ]}
      />



      <Navigation />

      <main className="pt-24 pb-16">
        <div className="container mx-auto px-6">
          {/* Header */}
          <motion.div
            initial="hidden"
            animate="visible"
            variants={containerVariants}
            className="mb-12"
          >
            <motion.div variants={headerVariants} className="flex items-center gap-4 mb-6">
              <Button
                variant="ghost"
                size="sm"
                asChild
                className="hover:bg-primary/10"
              >
                <Link to="/">
                  <ArrowLeft className="w-4 h-4 mr-2" />
                  {t("projects.back")}
                </Link>
              </Button>
            </motion.div>

            <motion.div variants={headerVariants} className="text-center mb-8">
              <p className="text-primary font-mono text-sm tracking-widest uppercase mb-2">
                {t("projects.subtitle")}
              </p>
              <h1 className="text-4xl md:text-5xl font-bold mb-4">
                <span className="bg-glow-gradient bg-clip-text text-transparent">
                  {t("projects.title")}
                </span>
              </h1>
              <p className="text-muted-foreground max-w-2xl mx-auto">
                {t("projects.description")}
              </p>
            </motion.div>

            {/* Technology Filter */}
            <TechnologyFilter
              technologies={allTechnologies}
              selectedTechnologies={selectedTechnologies}
              onToggle={toggleTechnology}
              onClear={clearFilters}
            />
          </motion.div>

          {/* Active Filters */}
          <AnimatePresence>
            {selectedTechnologies.length > 0 && (
              <motion.div
                initial={{ opacity: 0, height: 0 }}
                animate={{ opacity: 1, height: "auto" }}
                exit={{ opacity: 0, height: 0 }}
                className="mb-8"
              >
                <div className="flex flex-wrap items-center gap-2">
                  <span className="text-sm text-muted-foreground">
                    {t("projects.activeFilters")}:
                  </span>
                  {selectedTechnologies.map((tech) => (
                    <Badge
                      key={tech}
                      variant="secondary"
                      className="cursor-pointer hover:bg-destructive/20 transition-colors"
                      onClick={() => toggleTechnology(tech)}
                    >
                      {tech}
                      <X className="w-3 h-3 ml-1" />
                    </Badge>
                  ))}
                  <Button
                    variant="ghost"
                    size="sm"
                    onClick={clearFilters}
                    className="text-muted-foreground hover:text-foreground"
                  >
                    {t("projects.clearAll")}
                  </Button>
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          {/* Projects Grid */}
          <motion.div
            initial="hidden"
            animate="visible"
            variants={containerVariants}
            className="grid md:grid-cols-2 lg:grid-cols-3 gap-8"
          >
            <AnimatePresence mode="popLayout">
              {filteredProjects.map((project, index) => (
                <ProjectCard
                  key={project.id}
                  project={project}
                  index={index}
                  onClick={() => setSelectedProject(project)}
                />
              ))}
            </AnimatePresence>
          </motion.div>

          {/* Empty State */}
          {filteredProjects.length === 0 && (
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="text-center py-16"
            >
              <Filter className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
              <h3 className="text-xl font-semibold mb-2">{t("projects.noResults")}</h3>
              <p className="text-muted-foreground mb-4">
                {t("projects.noResultsDescription")}
              </p>
              <Button variant="outline" onClick={clearFilters}>
                {t("projects.clearFilters")}
              </Button>
            </motion.div>
          )}
        </div>
      </main>

      <Footer />

      {/* Project Detail Modal */}
      <ProjectDetail
        project={selectedProject}
        onClose={() => setSelectedProject(null)}
      />
    </div>
  );
};

export default Projects;
