"use client";

import { useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  X,
  CheckCircle2,
  ExternalLink,
  GitFork,
  Calendar,
  LayoutGrid,
  Award,
  ChevronLeft,
  ChevronRight,
  Images,
} from "lucide-react";

export function ProjectDetailModal({ project, onClose }: { project: any; onClose: () => void }) {
  const techStack: string[] = project?.techStack || [];
  const highlights: string[] = project?.highlights || [];

  // Build image gallery: prefer imageUrls array, fallback to single imageUrl
  const images: string[] =
    project?.imageUrls && project.imageUrls.length > 0
      ? project.imageUrls
      : project?.imageUrl
      ? [project.imageUrl]
      : [];

  const [activeIdx, setActiveIdx] = useState(0);

  function prev() {
    setActiveIdx((i) => (i === 0 ? images.length - 1 : i - 1));
  }
  function next() {
    setActiveIdx((i) => (i === images.length - 1 ? 0 : i + 1));
  }

  return (
    <AnimatePresence>
      {/* Backdrop */}
      <motion.div
        className="fixed inset-0 z-50 bg-black/70 backdrop-blur-md flex items-center justify-center p-4 lg:p-8"
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        onClick={onClose}
      >
        {/* Modal container — wide 2-col layout */}
        <motion.div
          className="relative w-full max-w-6xl bg-card border border-border/50 rounded-[2rem] shadow-2xl overflow-hidden flex flex-col lg:flex-row"
          style={{ maxHeight: "92vh" }}
          initial={{ scale: 0.95, opacity: 0, y: 20 }}
          animate={{ scale: 1, opacity: 1, y: 0 }}
          exit={{ scale: 0.95, opacity: 0, y: 20 }}
          transition={{ type: "spring", stiffness: 280, damping: 28 }}
          onClick={(e) => e.stopPropagation()}
        >
          {/* ── Close button ── */}
          <button
            onClick={onClose}
            className="absolute top-4 right-4 z-30 p-2.5 bg-black/40 hover:bg-black/70 backdrop-blur-md rounded-full text-white transition-all duration-300 hover:scale-110 shadow-lg"
          >
            <X size={18} />
          </button>

          {/* ══════════════════════════════════════════
              LEFT COLUMN — Details (scrollable)
          ══════════════════════════════════════════ */}
          <div className="flex flex-col lg:w-[42%] overflow-y-auto custom-scrollbar shrink-0">
            {/* Header */}
            <div className="px-7 pt-8 pb-5 border-b border-border/30">
              <h2 className="text-2xl md:text-3xl font-extrabold tracking-tight text-foreground leading-tight pr-10">
                {project.title}
              </h2>
              {project.year && (
                <div className="flex items-center gap-2 mt-3 text-sm font-medium text-muted-foreground">
                  <Calendar size={14} className="text-accent" />
                  <span>{project.year}</span>
                </div>
              )}
            </div>

            {/* Scrollable body */}
            <div className="flex-1 px-7 py-6 space-y-7">
              {/* Description */}
              <div>
                <p className="text-sm leading-relaxed text-muted-foreground">
                  {project.description}
                </p>
              </div>

              {/* Tech Stack */}
              <div>
                <div className="flex items-center gap-2 mb-3">
                  <LayoutGrid size={15} className="text-accent" />
                  <h4 className="text-sm font-bold uppercase tracking-wider text-muted-foreground">Tech Stack</h4>
                </div>
                {techStack.length > 0 ? (
                  <div className="flex flex-wrap gap-2">
                    {techStack.map((tech: string) => (
                      <span
                        key={tech}
                        className="px-3 py-1 rounded-lg text-xs font-semibold bg-accent/8 text-accent border border-accent/15 hover:border-accent/40 hover:bg-accent/15 transition-colors"
                      >
                        {tech}
                      </span>
                    ))}
                  </div>
                ) : (
                  <p className="text-xs text-muted-foreground italic">Belum ada tech stack.</p>
                )}
              </div>

              {/* Highlights */}
              <div>
                <div className="flex items-center gap-2 mb-3">
                  <Award size={15} className="text-emerald-500" />
                  <h4 className="text-sm font-bold uppercase tracking-wider text-muted-foreground">Pencapaian</h4>
                </div>
                {highlights.length > 0 ? (
                  <ul className="space-y-2">
                    {highlights.map((item: string, i: number) => (
                      <li
                        key={i}
                        className="flex items-start gap-2.5 p-2.5 rounded-lg bg-emerald-500/5 border border-emerald-500/10 hover:bg-emerald-500/10 transition-colors"
                      >
                        <CheckCircle2 size={14} className="text-emerald-500 mt-0.5 shrink-0" />
                        <span className="text-xs font-medium text-foreground/80">{item}</span>
                      </li>
                    ))}
                  </ul>
                ) : (
                  <p className="text-xs text-muted-foreground italic">Belum ada data pencapaian.</p>
                )}
              </div>
            </div>

            {/* Action buttons — sticky at bottom */}
            <div className="px-7 py-5 border-t border-border/30 flex flex-wrap gap-3 bg-muted/10 shrink-0">
              {project.liveUrl && (
                <a
                  href={project.liveUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex-1 min-w-[120px] flex items-center justify-center gap-2 px-5 py-2.5 rounded-xl bg-accent text-accent-foreground text-sm font-semibold shadow-lg shadow-accent/20 hover:shadow-xl hover:shadow-accent/40 hover:-translate-y-0.5 transition-all duration-300"
                >
                  <ExternalLink size={15} /> Kunjungi Web
                </a>
              )}
              {project.repoUrl && (
                <a
                  href={project.repoUrl}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex-1 min-w-[120px] flex items-center justify-center gap-2 px-5 py-2.5 rounded-xl bg-card border border-border/50 hover:border-border hover:bg-muted text-foreground text-sm font-semibold transition-all duration-300"
                >
                  <GitFork size={15} /> Source Code
                </a>
              )}
              {!project.liveUrl && !project.repoUrl && (
                <p className="text-xs text-muted-foreground italic">Tidak ada link yang tersedia.</p>
              )}
            </div>
          </div>

          {/* ══════════════════════════════════════════
              RIGHT COLUMN — Image Gallery
          ══════════════════════════════════════════ */}
          <div className="flex-1 flex flex-col bg-black/20 min-h-[300px] lg:min-h-0 border-t lg:border-t-0 lg:border-l border-border/20">
            {images.length > 0 ? (
              <>
                {/* Main image viewer */}
                <div className="relative flex-1 flex items-center justify-center overflow-hidden bg-black/30">
                  <AnimatePresence mode="wait">
                    <motion.img
                      key={activeIdx}
                      src={images[activeIdx]}
                      alt={`${project.title} — image ${activeIdx + 1}`}
                      className="max-w-full max-h-full object-contain select-none"
                      style={{ maxHeight: "calc(92vh - 120px)" }}
                      initial={{ opacity: 0, x: 30 }}
                      animate={{ opacity: 1, x: 0 }}
                      exit={{ opacity: 0, x: -30 }}
                      transition={{ duration: 0.25 }}
                      draggable={false}
                    />
                  </AnimatePresence>

                  {/* Arrow navigation (only when multiple images) */}
                  {images.length > 1 && (
                    <>
                      <button
                        onClick={prev}
                        className="absolute left-3 p-2.5 bg-black/50 hover:bg-black/80 rounded-full text-white transition-all hover:scale-110 backdrop-blur-sm shadow-lg"
                      >
                        <ChevronLeft size={20} />
                      </button>
                      <button
                        onClick={next}
                        className="absolute right-3 p-2.5 bg-black/50 hover:bg-black/80 rounded-full text-white transition-all hover:scale-110 backdrop-blur-sm shadow-lg"
                      >
                        <ChevronRight size={20} />
                      </button>
                    </>
                  )}

                  {/* Image counter badge */}
                  {images.length > 1 && (
                    <div className="absolute top-3 left-3 flex items-center gap-1.5 px-2.5 py-1 bg-black/50 backdrop-blur-sm rounded-full text-white text-xs font-semibold">
                      <Images size={12} />
                      {activeIdx + 1} / {images.length}
                    </div>
                  )}
                </div>

                {/* Thumbnail strip (only when multiple images) */}
                {images.length > 1 && (
                  <div className="flex gap-2 p-3 overflow-x-auto bg-black/40 shrink-0 custom-scrollbar">
                    {images.map((url, i) => (
                      <button
                        key={i}
                        onClick={() => setActiveIdx(i)}
                        className={`shrink-0 w-16 h-12 rounded-lg overflow-hidden border-2 transition-all hover:scale-105 ${
                          i === activeIdx
                            ? "border-accent shadow-lg shadow-accent/30"
                            : "border-white/10 opacity-60 hover:opacity-100"
                        }`}
                      >
                        <img src={url} alt={`thumb-${i}`} className="w-full h-full object-cover" />
                      </button>
                    ))}
                  </div>
                )}

                {/* Dot indicators */}
                {images.length > 1 && (
                  <div className="flex justify-center gap-1.5 py-2 bg-black/40 shrink-0">
                    {images.map((_, i) => (
                      <button
                        key={i}
                        onClick={() => setActiveIdx(i)}
                        className={`rounded-full transition-all ${
                          i === activeIdx
                            ? "w-5 h-2 bg-accent"
                            : "w-2 h-2 bg-white/30 hover:bg-white/60"
                        }`}
                      />
                    ))}
                  </div>
                )}
              </>
            ) : (
              /* No image placeholder */
              <div className="flex-1 flex flex-col items-center justify-center gap-4 text-muted-foreground/40 p-10">
                <LayoutGrid size={60} strokeWidth={1} />
                <p className="text-sm font-medium">Belum ada gambar</p>
              </div>
            )}
          </div>
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}
