import { motion, useReducedMotion } from "framer-motion";
import { ArrowUpRight, Layers } from "lucide-react";
import { useId, useState } from "react";
import { Link } from "react-router-dom";

interface ProjectPayload {
  _id: string;
  title: string;
  category: string[];
  isFeatured: boolean;
  technologies: string[];
  publishedYear: string | number;
  previewUrl: string;
  image?: string;
}

interface ProjectCardProps {
  project: ProjectPayload;
  index: number;
  isInView: boolean;
}

export function ProjectCard({ project, index, isInView }: ProjectCardProps) {
  const [mousePosition, setMousePosition] = useState({ x: 50, y: 50 });
  const [isHovered, setIsHovered] = useState(false);
  const shouldReduceMotion = useReducedMotion();
  const titleId = useId();

  const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
    if (shouldReduceMotion) return;
    const rect = e.currentTarget.getBoundingClientRect();
    const x = ((e.clientX - rect.left) / rect.width) * 100;
    const y = ((e.clientY - rect.top) / rect.height) * 100;
    setMousePosition({ x, y });
  };

  // Safe Fallback Asset Frame
  const projectImage =
    project.image ||
    "https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?q=80&w=800&auto=format&fit=crop";

  return (
    <motion.div
      initial={{ opacity: 0, y: shouldReduceMotion ? 0 : 40 }}
      animate={isInView ? { opacity: 1, y: 0 } : {}}
      transition={{
        duration: 0.5,
        delay: index * 0.05,
        ease: [0.215, 0.61, 0.355, 1],
      }}
      className="group relative bg-card border border-border/60 hover:border-primary/30 rounded-2xl overflow-hidden shadow-md hover:shadow-xl transition-all duration-300 flex flex-col h-full transform-gpu"
      onMouseMove={handleMouseMove}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => {
        setIsHovered(false);
        setMousePosition({ x: 50, y: 50 });
      }}
      aria-labelledby={titleId}
    >
      {/* Interactive Visual Window */}
      <div
        className="aspect-[16/10] overflow-hidden relative bg-muted w-full border-b border-border/40"
        style={{
          transform:
            isHovered && !shouldReduceMotion
              ? `perspective(1000px) rotateX(${(50 - mousePosition.y) * 0.06}deg) rotateY(${(mousePosition.x - 50) * 0.06}deg)`
              : "perspective(1000px) rotateX(0deg) rotateY(0deg)",
          transition: isHovered
            ? "transform 0.05s ease-out"
            : "transform 0.3s ease-out",
        }}
      >
        <img
          src={projectImage}
          alt={`Interface screenshot overview for ${project.title}`}
          className="w-full h-full object-cover transition-transform duration-700 ease-out group-hover:scale-[1.04]"
          loading="lazy"
        />

        {/* Techzaa Radial Spotlight Overlay */}
        {!shouldReduceMotion && (
          <div
            className="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-500 pointer-events-none mix-blend-screen"
            style={{
              background: `radial-gradient(circle 180px at ${mousePosition.x}% ${mousePosition.y}%, rgba(var(--primary-rgb, 99, 102, 241), 0.15), transparent 80%)`,
            }}
          />
        )}

        {/* Absolute Year Floating Tag */}
        <span className="absolute top-3 right-3 text-[10px] font-bold px-2 py-0.5 rounded bg-background/80 backdrop-blur-md border border-border/40 text-muted-foreground tracking-wider">
          {project.publishedYear}
        </span>
      </div>

      {/* Structured Informational Body Content */}
      <div className="p-6 flex flex-col flex-grow justify-between space-y-6">
        <div className="space-y-3">
          {/* Category Chip List Mapping handles strings or arrays cleanly */}
          <div
            className="flex flex-wrap gap-1"
            aria-label="Project classifications"
          >
            {Array.isArray(project.category) ? (
              project.category.slice(0, 3).map((cat) => (
                <span
                  key={cat}
                  className="inline-flex items-center text-[10px] font-bold uppercase tracking-wider text-primary bg-primary/5 border border-primary/10 px-2 py-0.5 rounded"
                >
                  {cat}
                </span>
              ))
            ) : (
              <span className="inline-flex items-center text-[10px] font-bold uppercase tracking-wider text-primary bg-primary/5 border border-primary/10 px-2 py-0.5 rounded">
                {project.category}
              </span>
            )}
          </div>

          {/* Title Identifier linked to parent card components via standard a11y specs */}
          <h3
            id={titleId}
            className="text-xl font-bold tracking-tight text-foreground leading-snug group-hover:text-primary transition-colors duration-200"
          >
            {project.title}
          </h3>

          {/* Previewing active Framework stacks cleanly underneath */}
          {project.technologies && project.technologies.length > 0 && (
            <div className="flex flex-wrap gap-1 pt-1">
              {project.technologies.slice(0, 4).map((tech) => (
                <span
                  key={tech}
                  className="text-[11px] font-medium text-muted-foreground bg-secondary/40 px-2 py-0.5 rounded border border-border/30"
                >
                  {tech}
                </span>
              ))}
              {project.technologies.length > 4 && (
                <span className="text-[10px] font-semibold text-muted-foreground/60 px-1.5 py-0.5">
                  +{project.technologies.length - 4} more
                </span>
              )}
            </div>
          )}
        </div>

        {/* Action Controls Matrix Bar */}
        <div className="flex items-center justify-between pt-4 border-t border-border/40 w-full text-xs font-semibold tracking-wide">
          <Link
            to={`/projects/${project._id}`}
            className="inline-flex items-center text-muted-foreground hover:text-foreground transition-colors py-1 focus-visible:outline-none focus-visible:underline"
            aria-label={`Read technical case documentation for ${project.title}`}
          >
            <Layers className="w-3.5 h-3.5 mr-1.5 text-primary/70" />
            Case Study
          </Link>

          <a
            href={project.previewUrl}
            target="_blank"
            rel="noopener noreferrer"
            className="inline-flex items-center text-primary hover:opacity-80 transition-opacity py-1 focus-visible:outline-none focus-visible:underline"
            aria-label={`Launch deployment window for ${project.title}`}
          >
            Live Platform
            <ArrowUpRight className="w-3.5 h-3.5 ml-1 transition-transform group-hover:translate-x-0.5 group-hover:-translate-y-0.5" />
          </a>
        </div>
      </div>
    </motion.div>
  );
}
