import PageTransition from "@/components/home/PageTransition";
import { ProjectCard } from "@/components/home/ProjectCard";
import { Button } from "@/components/ui/button";
import { useProjects } from "@/hooks/queries/useProjects";
import { AnimatePresence, motion, useReducedMotion } from "framer-motion";
import {
  ArrowLeft,
  Brain,
  Cloud,
  Globe,
  Layers,
  Search,
  Smartphone,
  Sparkles,
  Workflow,
} from "lucide-react";
import { useDeferredValue, useMemo, useState } from "react";
import { Link } from "react-router-dom";

const CATEGORIES = [
  { id: "all", name: "All Work", icon: Layers },
  { id: "web", name: "Web Systems", icon: Globe },
  { id: "mobile", name: "Mobile", icon: Smartphone },
  { id: "ai", name: "AI & ML", icon: Brain },
  { id: "cloud", name: "Cloud Platforms", icon: Cloud },
  { id: "devops", name: "DevOps", icon: Workflow },
];

const containerVariants = {
  hidden: { opacity: 0 },
  visible: {
    opacity: 1,
    transition: { staggerChildren: 0.04 },
  },
};

export default function Projects() {
  const { data: projectsData, isLoading, isError } = useProjects();
  const shouldReduceMotion = useReducedMotion();

  const [activeCategory, setActiveCategory] = useState("all");
  const [searchQuery, setSearchQuery] = useState("");

  const deferredSearchQuery = useDeferredValue(searchQuery);

  const filteredProjects = useMemo(() => {
    const projects = projectsData?.data?.data || projectsData?.data || [];
    if (!Array.isArray(projects)) return [];

    return projects.filter((project) => {
      const matchesCategory =
        activeCategory === "all" ||
        (Array.isArray(project.category)
          ? project.category.some(
              (cat: string) =>
                cat.toLowerCase() === activeCategory.toLowerCase() ||
                cat.toLowerCase().includes(activeCategory.toLowerCase()),
            )
          : project.category?.toLowerCase() === activeCategory.toLowerCase());

      const normalizedSearch = deferredSearchQuery.trim().toLowerCase();
      const matchesSearch =
        normalizedSearch === "" ||
        project.title?.toLowerCase().includes(normalizedSearch) ||
        project.description?.toLowerCase().includes(normalizedSearch) ||
        (Array.isArray(project.technologies) &&
          project.technologies.some((tech: string) =>
            tech.toLowerCase().includes(normalizedSearch),
          ));

      return matchesCategory && matchesSearch;
    });
  }, [projectsData, activeCategory, deferredSearchQuery]);

  return (
    <PageTransition>
      <div className="min-h-screen bg-background text-foreground antialiased selection:bg-primary/20">
        <section className="pt-32 pb-12 relative overflow-hidden border-b border-border/40">
          <div className="container mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
            {/* Back Arrow Wrapper - Kept clean on left side */}
            <motion.div
              initial={{ opacity: 0, x: shouldReduceMotion ? 0 : -10 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.3 }}
              className="w-full flex justify-start"
            >
              <Button
                asChild
                variant="ghost"
                size="sm"
                className="mb-6 group text-muted-foreground hover:text-foreground"
              >
                <Link to="/">
                  <ArrowLeft className="w-4 h-4 mr-2 transition-transform group-hover:-translate-x-1" />
                  Back to Home
                </Link>
              </Button>
            </motion.div>

            <div className="w-full flex flex-col items-center justify-center text-center">
              <div className="max-w-3xl mb-12">
                <motion.h1
                  initial={{ opacity: 0, y: shouldReduceMotion ? 0 : 15 }}
                  animate={{ opacity: 1, y: 0 }}
                  className="text-4xl sm:text-5xl lg:text-6xl font-black tracking-tight leading-none mb-4"
                >
                  All Projects
                </motion.h1>
                <motion.p
                  initial={{ opacity: 0, y: shouldReduceMotion ? 0 : 15 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: 0.05 }}
                  className="text-base sm:text-lg text-muted-foreground leading-relaxed max-w-2xl mx-auto"
                >
                  A high-fidelity showroom tracking production ecosystems, AI
                  operations, and cloud architectures compiled by Techzaa.
                </motion.p>
              </div>

              {/* Interface Control Bar Matrix - Fully Centered Substructures */}
              <motion.div
                initial={{ opacity: 0, y: shouldReduceMotion ? 0 : 15 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.1 }}
                className="space-y-6 w-full pt-6 border-t border-border/40 flex flex-col items-center justify-center"
              >
                {/* Search input container centralized down the layout grid */}
                <div className="relative max-w-md w-full group mx-auto">
                  <Search className="absolute left-3.5 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground group-focus-within:text-primary transition-colors" />
                  <input
                    type="text"
                    placeholder="Query by parameter, core feature, or framework stack..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="w-full pl-10 pr-4 py-2 text-sm rounded-xl border border-border bg-card/60 placeholder:text-muted-foreground/60 focus:outline-none focus:ring-2 focus:ring-primary/30 transition-all shadow-sm"
                    aria-label="Search deployment records"
                  />
                </div>

                {/* Categories Tab Matrix - Wrapped with center axis parameters */}
                <div
                  className="flex flex-wrap items-center justify-center gap-2 max-w-2xl w-full"
                  role="tablist"
                  aria-label="Project Filtering Options"
                >
                  {CATEGORIES.map((cat) => {
                    const Icon = cat.icon;
                    const isActive = activeCategory === cat.id;

                    return (
                      <Button
                        key={cat.id}
                        variant={isActive ? "default" : "outline"}
                        onClick={() => setActiveCategory(cat.id)}
                        role="tab"
                        aria-selected={isActive}
                        className="rounded-xl text-xs font-semibold tracking-wide h-9 px-4 transition-all duration-200"
                      >
                        <Icon className="w-3.5 h-3.5 mr-2 opacity-80" />
                        {cat.name}
                      </Button>
                    );
                  })}
                </div>
              </motion.div>
            </div>
          </div>
        </section>

        {/* Projects View Output Section */}
        <section className="py-16 bg-background">
          <div className="container mx-auto px-4 sm:px-6 lg:px-8">
            {isLoading && (
              <div
                className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8"
                role="status"
                aria-label="Loading project payload"
              >
                {[...Array(6)].map((_, idx) => (
                  <div
                    key={idx}
                    className="bg-card border border-border/40 rounded-2xl p-4 space-y-6 animate-pulse"
                  >
                    <div className="aspect-[16/10] bg-muted rounded-xl w-full" />
                    <div className="space-y-3 px-2">
                      <div className="h-4 bg-muted rounded-md w-1/3" />
                      <div className="h-6 bg-muted rounded-md w-3/4" />
                      <div className="h-4 bg-muted rounded-md w-full" />
                    </div>
                  </div>
                ))}
              </div>
            )}

            {isError && (
              <div className="text-center py-16 border border-destructive/20 bg-destructive/5 rounded-2xl max-w-lg mx-auto p-6 space-y-3">
                <p className="text-base font-bold text-foreground">
                  API Synchronization Failure
                </p>
                <p className="text-xs text-muted-foreground leading-normal">
                  Could not safely sync target records from Techzaa's data layer
                  cluster. Confirm connection status parameters.
                </p>
              </div>
            )}

            {!isLoading && !isError && (
              <AnimatePresence mode="popLayout">
                {filteredProjects.length > 0 ? (
                  <motion.div
                    key={`${activeCategory}-${deferredSearchQuery}`}
                    variants={containerVariants}
                    initial="hidden"
                    animate="visible"
                    exit="hidden"
                    className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 items-stretch"
                  >
                    {filteredProjects.map((project, idx) => (
                      <motion.div
                        layout={!shouldReduceMotion}
                        key={project._id}
                        className="h-full"
                      >
                        <ProjectCard
                          project={{
                            _id: project._id,
                            title: project.title,
                            category: Array.isArray(project.category)
                              ? project.category
                              : [project.category],
                            isFeatured: project.isFeatured || false,
                            technologies: project.technologies || [],
                            publishedYear:
                              project.publishedYear || project.year || "2026",
                            previewUrl:
                              project.previewUrl || project.liveUrl || "#",
                            image: project.image,
                          }}
                          index={idx}
                          isInView={true}
                        />
                      </motion.div>
                    ))}
                  </motion.div>
                ) : (
                  <motion.div
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    className="text-center py-24 border border-dashed border-border rounded-2xl max-w-md mx-auto p-8 space-y-2"
                  >
                    <Sparkles className="w-5 h-5 text-muted-foreground/60 mx-auto" />
                    <h3 className="text-sm font-bold text-foreground">
                      No Projects Located
                    </h3>
                    <p className="text-xs text-muted-foreground leading-relaxed">
                      Your lookup parameter variations produced zero operational
                      matches in our architecture records.
                    </p>
                  </motion.div>
                )}
              </AnimatePresence>
            )}
          </div>
        </section>
      </div>
    </PageTransition>
  );
}
