import PageTransition from "@/components/home/PageTransition";
import { Button } from "@/components/ui/button";
import { useProjectById } from "@/hooks/queries/useProjects";
import { motion, useReducedMotion } from "framer-motion";
import {
  AlertCircle,
  Calendar,
  CheckCircle,
  ChevronRight,
  Clock,
  ExternalLink,
  HelpCircle,
  Sliders,
  Sparkles,
} from "lucide-react";
import { Link, useNavigate, useParams } from "react-router-dom";

// Standardizing backend data matching layer safely
interface BackendProjectPayload {
  _id: string;
  title: string;
  description: string;
  category: string[];
  status: string;
  isFeatured: boolean;
  image: string;
  imageGallery: string[];
  technologies: string[];
  publishedYear: string | number;
  problem: string;
  solutions: string;
  challenges: string;
  workingDuration: string;
  previewUrl: string;
  features: string[];
}

export default function ProjectDetails() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const shouldReduceMotion = useReducedMotion();
  const { data, isLoading, isError } = useProjectById(id || "");

  const project: BackendProjectPayload | null =
    data?.data?.data || data?.data || data || null;

  const faderUpVariants = {
    hidden: { opacity: 0, y: shouldReduceMotion ? 0 : 20 },
    visible: (custom: number) => ({
      opacity: 1,
      y: 0,
      transition: {
        duration: 0.5,
        delay: custom * 0.08,
        ease: [0.215, 0.61, 0.355, 1],
      },
    }),
  };

  if (isLoading) {
    return (
      <PageTransition>
        <div
          className="min-h-screen bg-background flex items-center justify-center"
          role="status"
          aria-live="polite"
        >
          <div className="flex flex-col items-center gap-4">
            <div className="relative w-10 h-10">
              <div className="absolute inset-0 border-4 border-primary/10 rounded-full" />
              <div className="absolute inset-0 border-4 border-primary border-t-transparent rounded-full animate-spin" />
            </div>
            <span className="text-xs font-semibold tracking-widest text-muted-foreground uppercase animate-pulse">
              Parsing Techzaa Case Asset...
            </span>
          </div>
        </div>
      </PageTransition>
    );
  }

  if (isError || !project) {
    return (
      <PageTransition>
        <div className="min-h-screen bg-background flex items-center justify-center p-6">
          <div className="text-center max-w-sm border border-destructive/20 bg-card p-8 rounded-2xl shadow-xl space-y-6">
            <div className="inline-flex p-3 bg-destructive/10 rounded-full text-destructive">
              <AlertCircle className="w-5 h-5" />
            </div>
            <div className="space-y-2">
              <h1 className="text-xl font-bold tracking-tight">
                Deployment Not Located
              </h1>
              <p className="text-xs text-muted-foreground leading-relaxed">
                The targeted project record configuration cannot be pulled from
                the API ecosystem.
              </p>
            </div>
            <Button
              onClick={() => navigate("/projects")}
              className="w-full rounded-xl text-xs font-semibold uppercase tracking-wider"
            >
              Return to home
            </Button>
          </div>
        </div>
      </PageTransition>
    );
  }

  return (
    <PageTransition>
      <div className="min-h-screen bg-background text-foreground selection:bg-primary/20 selection:text-primary antialiased">
        {/* HERO SECTION - Architectural Dynamic Header */}
        <section className="pt-36 pb-16 relative overflow-hidden">
          <div className="container mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
            {/* Dynamic Breadcrumbs */}
            <nav aria-label="Breadcrumb" className="mb-10">
              <ol className="flex items-center space-x-2 text-xs font-medium text-muted-foreground">
                <li>
                  <Link
                    to="/"
                    className="hover:text-primary transition-colors focus-visible:outline-none focus-visible:underline"
                  >
                    Home
                  </Link>
                </li>
                <li className="flex items-center space-x-2">
                  <ChevronRight className="w-3 h-3 opacity-60" />
                  <Link
                    to="/projects"
                    className="hover:text-primary transition-colors focus-visible:outline-none focus-visible:underline"
                  >
                    Projects
                  </Link>
                </li>
                <li className="flex items-center space-x-2" aria-current="page">
                  <ChevronRight className="w-3 h-3 opacity-60" />
                  <span className="text-foreground font-semibold truncate max-w-[200px]">
                    {project.title}
                  </span>
                </li>
              </ol>
            </nav>

            {/* Asymmetric Split Layout */}
            <div className="grid grid-cols-1 lg:grid-cols-12 gap-12 items-start">
              {/* Primary Metas Block */}
              <div className="lg:col-span-7 space-y-6">
                <motion.div
                  initial="hidden"
                  animate="visible"
                  custom={0}
                  className="flex flex-wrap gap-1.5"
                >
                  {Array.isArray(project.category) ? (
                    project.category.map((cat) => (
                      <span
                        key={cat}
                        className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded bg-secondary text-secondary-foreground border border-border/80 text-[11px] font-semibold tracking-wide"
                      >
                        {cat}
                      </span>
                    ))
                  ) : (
                    <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded bg-secondary text-secondary-foreground border border-border/80 text-[11px] font-semibold tracking-wide">
                      {project.category}
                    </span>
                  )}
                </motion.div>

                <motion.h1
                  animate="visible"
                  custom={1}
                  className="text-3xl sm:text-4xl lg:text-5xl font-black tracking-tight text-foreground leading-[1.1]"
                >
                  {project.title}
                </motion.h1>

                <motion.p
                  initial="hidden"
                  animate="visible"
                  custom={2}
                  className="text-base sm:text-lg text-muted-foreground leading-relaxed max-w-2xl"
                >
                  {project.description}
                </motion.p>

                {/* Primary Interaction Arrays */}
                <motion.div
                  initial="hidden"
                  animate="visible"
                  custom={3}
                  className="flex flex-col sm:flex-row gap-3 pt-2"
                >
                  <Button
                    asChild
                    size="lg"
                    className="rounded-xl font-semibold tracking-wide shadow-lg shadow-primary/5 transition-transform active:scale-[0.98]"
                  >
                    <a
                      href={project.previewUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      <ExternalLink className="w-4 h-4 mr-2" />
                      Live Preview Link
                    </a>
                  </Button>
                </motion.div>
              </div>

              {/* Cover Interactive Card Frame */}
              <div className="lg:col-span-5 w-full">
                <motion.div
                  initial={{ opacity: 0, scale: shouldReduceMotion ? 1 : 0.97 }}
                  animate={{ opacity: 1, scale: 1 }}
                  transition={{ duration: 0.5 }}
                  className="relative rounded-2xl overflow-hidden border border-border bg-card aspect-[4/3] shadow-lg transform-gpu"
                >
                  <img
                    src={project.image}
                    alt={`Case Application mockup frame for ${project.title}`}
                    className="w-full h-full object-cover object-center"
                    loading="eager"
                  />
                </motion.div>
              </div>
            </div>
          </div>
        </section>

        {/* METADATA BAR SECTION */}
        <section
          className="py-8 bg-secondary/20 border-y border-border/40"
          aria-label="System parameters"
        >
          <div className="container mx-auto px-4 sm:px-6 lg:px-8">
            <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
              {[
                {
                  label: "Deployment Year",
                  value: project.publishedYear,
                  icon: Calendar,
                },
                {
                  label: "Production Period",
                  value: project.workingDuration,
                  icon: Clock,
                },
                {
                  label: "Project Status",
                  value: project.status,
                  icon: Sliders,
                },
              ].map((item) => (
                <div
                  key={item.label}
                  className="p-4 bg-card border border-border/60 rounded-xl flex items-center justify-between shadow-sm"
                >
                  <div className="space-y-0.5 truncate mr-2">
                    <span className="block text-[10px] font-bold tracking-wider uppercase text-muted-foreground">
                      {item.label}
                    </span>
                    <span className="block text-sm font-bold text-foreground truncate">
                      {item.value}
                    </span>
                  </div>
                  <item.icon className="w-4 h-4 text-primary opacity-70 flex-shrink-0" />
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* COMPREHENSIVE CASE LOGIC SECTION */}
        <section className="py-20 bg-background">
          <div className="container mx-auto px-4 sm:px-6 lg:px-8">
            <div className="grid grid-cols-1 lg:grid-cols-12 gap-12 lg:gap-16 items-start">
              {/* Engineering Metrics Column (Left side) */}
              <div className="lg:col-span-6 space-y-10">
                {project.problem && (
                  <div className="space-y-3">
                    <h3 className="text-lg font-bold tracking-tight text-foreground flex items-center gap-2">
                      <HelpCircle className="w-4 h-4 text-primary" />
                      The Structural Problem
                    </h3>
                    <p className="text-sm text-muted-foreground leading-relaxed bg-secondary/10 border border-border/40 p-4 rounded-xl">
                      {project.problem}
                    </p>
                  </div>
                )}

                {project.solutions && (
                  <div className="space-y-3">
                    <h3 className="text-lg font-bold tracking-tight text-foreground flex items-center gap-2">
                      <CheckCircle className="w-4 h-4 text-primary" />
                      Our Applied Strategy
                    </h3>
                    <p className="text-sm text-muted-foreground leading-relaxed bg-primary/5 border border-primary/10 p-4 rounded-xl">
                      {project.solutions}
                    </p>
                  </div>
                )}

                {project.challenges && (
                  <div className="space-y-3 border-t border-border/40 pt-6">
                    <h3 className="text-lg font-bold tracking-tight text-foreground">
                      Critical Bottlenecks Resolved
                    </h3>
                    <p className="text-sm text-muted-foreground leading-relaxed">
                      {project.challenges}
                    </p>
                  </div>
                )}
              </div>

              <div className="lg:col-span-6 space-y-10">
                {project.technologies && project.technologies.length > 0 && (
                  <div className="space-y-4">
                    <h3 className="text-sm font-bold tracking-wider  uppercase">
                      Tech Stack
                    </h3>
                    <div className="flex flex-wrap gap-1.5">
                      {project.technologies.map((tech) => (
                        <span
                          key={tech}
                          className="px-3 py-1 bg-card text-xs font-semibold rounded border border-border/80 text-foreground transition-colors cursor-default hover:bg-secondary/40"
                        >
                          {tech}
                        </span>
                      ))}
                    </div>
                  </div>
                )}

                {project.features && project.features.length > 0 && (
                  <div className="space-y-4 border-t border-border/40 pt-6">
                    <h3 className="text-lg font-bold tracking-tight text-foreground flex items-center gap-2">
                      <Sparkles className="w-4 h-4 text-primary" />
                      Delivered Platform Capabilities
                    </h3>
                    <ul className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
                      {project.features.map((feature, idx) => (
                        <li
                          key={idx}
                          className="flex items-center gap-2 text-xs text-muted-foreground bg-card border border-border/40 p-2.5 rounded-lg"
                        >
                          <div className="w-1.5 h-1.5 rounded-full bg-primary flex-shrink-0" />
                          <span className="truncate">{feature}</span>
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
              </div>
            </div>
          </div>
        </section>

        {/* PLATFORM PRESENTATION SHOWCASE GALLERY */}
        {project.imageGallery && project.imageGallery.length > 0 && (
          <section className="py-20 border-t border-border/40 bg-secondary/10">
            <div className="container mx-auto px-4 sm:px-6 lg:px-8">
              <div className="max-w-xl mx-auto text-center mb-12 space-y-1">
                <h2 className="text-xl sm:text-2xl font-bold tracking-tight">
                  Platform Interface Metrics
                </h2>
                <p className="text-xs text-muted-foreground">
                  Operational state validation screens captured during
                  deployment execution.
                </p>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                {project.imageGallery.map((image, index) => (
                  <motion.div
                    key={index}
                    initial={{ opacity: 0, y: shouldReduceMotion ? 0 : 15 }}
                    whileInView={{ opacity: 1, y: 0 }}
                    viewport={{ once: true, margin: "-20px" }}
                    transition={{ delay: index * 0.05, duration: 0.4 }}
                    className="group relative aspect-[4/3] rounded-xl overflow-hidden border border-border bg-card shadow-sm transform-gpu"
                  >
                    <img
                      src={image}
                      alt={`Platform runtime verification graphic state capture ${index + 1}`}
                      className="w-full h-full object-cover object-center transition-transform duration-500 group-hover:scale-[1.02]"
                      loading="lazy"
                    />
                  </motion.div>
                ))}
              </div>
            </div>
          </section>
        )}
      </div>
    </PageTransition>
  );
}
