import PageTransition from "@/components/home/PageTransition";
import { Button } from "@/components/ui/button";
import { useProjects } from "@/hooks/queires/useProjects";
import { AnimatePresence, motion } from "framer-motion";
import {
  ArrowLeft,
  Brain,
  Cloud,
  ExternalLink,
  Github,
  Globe,
  Loader2,
  Search,
  Smartphone,
  Workflow,
} from "lucide-react";
import { useMemo, useState } from "react";
import { Link } from "react-router-dom";

const categories = [
  { id: "all", name: "All Projects", icon: null },
  { id: "web", name: "Web", icon: Globe },
  { id: "mobile", name: "Mobile", icon: Smartphone },
  { id: "ai", name: "AI", icon: Brain },
  { id: "cloud", name: "Cloud", icon: Cloud },
  { id: "devops", name: "DEVOPS", icon: Workflow },
];

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

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

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

  const filteredProjects = useMemo(() => {
    const projects = projectsData?.data?.data?.result || [];
    if (!projects) return [];
    return projects.filter((project) => {
      const matchesCategory =
        activeCategory === "all" || project.category === activeCategory;

      const matchesSearch =
        searchQuery.trim() === "" ||
        project.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
        project.description.toLowerCase().includes(searchQuery.toLowerCase()) ||
        project.technologies.some((tech: string) =>
          tech.toLowerCase().includes(searchQuery.toLowerCase()),
        );

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

  return (
    <PageTransition>
      <div className="min-h-screen bg-background overflow-x-hidden text-foreground antialiased">
        {/* Hero Section */}
        <section className="pt-32 pb-16 relative overflow-hidden border-b border-primary/10">
          <div className="absolute inset-0 pointer-events-none select-none">
            <div className="absolute top-1/4 left-1/4 w-96 h-96 bg-primary/10 rounded-full blur-3xl" />
            <div className="absolute bottom-0 right-1/4 w-64 h-64 bg-accent/20 rounded-full blur-3xl" />
          </div>

          <div className="container mx-auto px-4 relative z-10">
            {/* Back Button */}
            <motion.div
              initial={{ opacity: 0, x: -20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ duration: 0.4 }}
            >
              <Link to="/">
                <Button variant="ghost" className="mb-8 group h-10 px-4">
                  <ArrowLeft className="w-4 h-4 mr-2 transition-transform group-hover:-translate-x-1" />
                  Back to Home
                </Button>
              </Link>
            </motion.div>

            {/* Header */}
            <motion.div
              initial={{ opacity: 0, y: 15 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5 }}
              className="text-center mb-10 max-w-3xl mx-auto"
            >
              <h1 className="text-4xl md:text-6xl font-extrabold tracking-tight mb-4 bg-gradient-to-r from-primary via-primary/80 to-accent bg-clip-text text-transparent">
                Our Projects
              </h1>
              <p className="text-muted-foreground text-lg md:text-xl leading-relaxed max-w-2xl mx-auto">
                Explore our portfolio of innovative solutions designed to scale
                and transform businesses across industries.
              </p>
            </motion.div>

            {/* Interactive Search and Filter Section */}
            <motion.div
              initial={{ opacity: 0, y: 15 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.5, delay: 0.1 }}
              className="flex flex-col items-center gap-6 mb-12"
            >
              {/* Search Bar */}
              <div className="relative w-full max-w-md">
                <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-5 h-5 text-muted-foreground" />
                <input
                  type="text"
                  placeholder="Search projects, tech, or keywords..."
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  className="w-full pl-10 pr-4 py-2.5 rounded-full border border-border/50 bg-background/50 backdrop-blur-sm focus:outline-none focus:ring-2 focus:ring-primary/40 transition-all text-sm shadow-sm"
                  aria-label="Search projects"
                />
              </div>

              {/* Filter Tabs */}
              <div className="flex flex-wrap justify-center gap-2 max-w-4xl">
                {categories.map((category) => {
                  const Icon = category.icon;
                  const isActive = activeCategory === category.id;

                  return (
                    <Button
                      key={category.id}
                      variant={isActive ? "default" : "outline"}
                      onClick={() => setActiveCategory(category.id)}
                      aria-pressed={isActive}
                      className={`rounded-full px-5 py-2 text-sm font-medium transition-all duration-300 ${
                        isActive
                          ? "bg-primary text-primary-foreground shadow-sm shadow-primary/20"
                          : "border-border/60 hover:bg-muted/50"
                      }`}
                    >
                      {Icon && <Icon className="w-4 h-4 mr-2" />}
                      {category.name}
                    </Button>
                  );
                })}
              </div>
            </motion.div>
          </div>
        </section>

        {/* Projects Grid */}
        <section className="py-20 bg-background/50">
          <div className="container mx-auto px-4">
            {/* Loading / Error State */}
            {isLoading && (
              <div className="flex flex-col items-center justify-center py-24 gap-4 text-muted-foreground animate-pulse">
                <Loader2 className="w-8 h-8 animate-spin text-primary" />
                <span className="text-sm font-medium">Loading projects...</span>
              </div>
            )}

            {isError && (
              <div className="text-center py-20 text-destructive">
                <p className="text-lg font-semibold mb-2">
                  Failed to load projects.
                </p>
                <p className="text-sm text-muted-foreground">
                  Please check your network connection or try again later.
                </p>
              </div>
            )}

            {!isLoading && !isError && (
              <AnimatePresence mode="wait">
                <motion.div
                  key={`${activeCategory}-${searchQuery}`}
                  variants={containerVariants}
                  initial="hidden"
                  animate="visible"
                  exit="hidden"
                  className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8"
                >
                  {filteredProjects.map((project) => (
                    <motion.article
                      key={project._id}
                      layout
                      className="group flex flex-col justify-between bg-card/40 border border-border/50 backdrop-blur-sm rounded-3xl overflow-hidden hover:border-primary/50 transition-all duration-500 hover:shadow-xl hover:shadow-accent/5 p-4"
                    >
                      <div>
                        {/* Project Image */}
                        <div className="relative h-56 rounded-2xl overflow-hidden mb-6">
                          <img
                            src={project.image}
                            alt={project.title}
                            loading="lazy"
                            className="w-full h-full object-cover transition-transform duration-700 ease-out group-hover:scale-105"
                          />
                          <div className="absolute inset-0 bg-gradient-to-t from-background/90 via-background/20 to-transparent opacity-80" />

                          {/* Category Badge */}
                          <div className="absolute top-4 left-4">
                            <span className="px-3 py-1 rounded-full bg-primary/20 text-primary text-xs font-semibold backdrop-blur-md border border-primary/20">
                              {
                                categories.find(
                                  (c) => c.id === project.category,
                                )?.name
                              }
                            </span>
                          </div>

                          {/* Quick External Links */}
                          <div className="absolute top-4 right-4 flex gap-2 opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                            {project.liveUrl && (
                              <a
                                href={project.liveUrl}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="p-2 rounded-full bg-background/80 backdrop-blur-sm border border-border/40 hover:bg-primary/20 transition-colors"
                                aria-label={`View live project: ${project.title}`}
                              >
                                <ExternalLink className="w-4 h-4" />
                              </a>
                            )}
                            {project.githubUrl && (
                              <a
                                href={project.githubUrl}
                                target="_blank"
                                rel="noopener noreferrer"
                                className="p-2 rounded-full bg-background/80 backdrop-blur-sm border border-border/40 hover:bg-primary/20 transition-colors"
                                aria-label={`View GitHub repository for: ${project.title}`}
                              >
                                <Github className="w-4 h-4" />
                              </a>
                            )}
                          </div>
                        </div>

                        {/* Title & Description */}
                        <div className="px-2">
                          <div className="flex items-center gap-3 text-xs font-medium text-muted-foreground mb-3">
                            <span>{project.client}</span>
                            <span className="w-1.5 h-1.5 rounded-full bg-muted-foreground/40" />
                            <span>{project.year}</span>
                          </div>

                          <h3 className="text-xl font-bold tracking-tight mb-3 group-hover:text-primary transition-colors line-clamp-1">
                            <Link to={`/projects/${project._id}`}>
                              {project.title}
                            </Link>
                          </h3>

                          <p className="text-muted-foreground text-sm leading-relaxed mb-6 line-clamp-3">
                            {project.description}
                          </p>
                        </div>
                      </div>

                      {/* Technologies and Detail Navigation */}
                      <div className="px-2">
                        <div className="flex flex-wrap gap-1.5 max-h-16 overflow-hidden mb-4">
                          {project.technologies
                            .slice(0, 5)
                            .map((tech: string) => (
                              <span
                                key={tech}
                                className="px-2.5 py-0.5 rounded-md bg-primary text-primary-foreground text-xs font-semibold tracking-wide"
                              >
                                {tech}
                              </span>
                            ))}
                          {project.technologies.length > 5 && (
                            <span className="px-2.5 py-0.5 rounded-md bg-secondary text-secondary-foreground text-xs font-semibold tracking-wide">
                              +{project.technologies.length - 5}
                            </span>
                          )}
                        </div>

                        <div className="flex justify-end pt-2 border-t border-border/30">
                          <Link to={`/projects/${project._id}`}>
                            <Button
                              variant="link"
                              size="sm"
                              className="text-xs text-primary p-0 h-auto font-semibold group/btn"
                            >
                              View Details
                            </Button>
                          </Link>
                        </div>
                      </div>
                    </motion.article>
                  ))}
                </motion.div>
              </AnimatePresence>
            )}

            {/* Empty State */}
            {!isLoading && !isError && filteredProjects.length === 0 && (
              <motion.div
                initial={{ opacity: 0, y: 10 }}
                animate={{ opacity: 1, y: 0 }}
                className="text-center py-20"
              >
                <p className="text-muted-foreground text-lg">
                  No projects match your current search or category.
                </p>
              </motion.div>
            )}
          </div>
        </section>
      </div>
    </PageTransition>
  );
}
