import { useState } from "react";
import { useParams, Link } from "wouter";
import { motion } from "framer-motion";
import { Star, ArrowLeft, Heart, MapPin, Languages, Activity, X, ZoomIn, ZoomOut, ChevronLeft, ChevronRight } from "lucide-react";
import { COMPANIONS } from "@/lib/mock-data";
import InquiryModal from "@/components/InquiryModal";
import galleryImage1 from "@/components/images/download (2).jpeg";
import galleryImage2 from "@/components/images/images.jpeg";
import galleryImage3 from "@/components/images/download.jpeg";
import galleryImage4 from "@/components/images/download (1).jpeg";

const DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
const HOURS = ["10am", "12pm", "2pm", "4pm", "6pm", "8pm"];

export default function CompanionDetail() {
  const { id } = useParams();
  const c = COMPANIONS.find(x => x.id === id);
  const [fav, setFav] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  const [lightboxOpen, setLightboxOpen] = useState(false);
  const [imageZoomed, setImageZoomed] = useState(false);

  if (!c) {
    return (
      <div className="pt-32 text-center">
        <h2 className="font-serif text-3xl text-foreground mb-4">Companion not found</h2>
        <Link href="/companions">
          <span className="text-primary text-sm cursor-pointer hover:underline">Back to Companions</span>
        </Link>
      </div>
    );
  }

  const gradients = [
    "from-amber-900/60 via-stone-900 to-stone-950",
    "from-rose-900/40 via-stone-900 to-stone-950",
    "from-emerald-900/40 via-stone-900 to-stone-950",
    "from-indigo-900/40 via-stone-900 to-stone-950",
    "from-amber-800/50 via-stone-900 to-stone-950",
    "from-purple-900/40 via-stone-900 to-stone-950",
    "from-teal-900/40 via-stone-900 to-stone-950",
    "from-orange-900/40 via-stone-900 to-stone-950",
  ];
  const grad = gradients[parseInt(c.id) % gradients.length];

  const gallery: string[] = (c as { gallery?: string[] }).gallery || [galleryImage1, galleryImage2, galleryImage3, galleryImage4];
  const collageImages = Array.from({ length: Math.max(6, gallery.length) }, (_, idx) => gallery[idx % gallery.length]);
  const openLightbox = (idx: number) => {
    setCurrentImageIndex(idx);
    setImageZoomed(false);
    setLightboxOpen(true);
  };
  const closeLightbox = () => {
    setLightboxOpen(false);
    setImageZoomed(false);
  };
  const showPrevImage = () => {
    setCurrentImageIndex((idx) => (idx - 1 + gallery.length) % gallery.length);
    setImageZoomed(false);
  };
  const showNextImage = () => {
    setCurrentImageIndex((idx) => (idx + 1) % gallery.length);
    setImageZoomed(false);
  };

  const availability: Record<string, string[]> = {
    Mon: ["2pm", "4pm", "6pm"],
    Tue: ["10am", "12pm"],
    Wed: ["4pm", "6pm", "8pm"],
    Thu: ["12pm", "2pm", "4pm"],
    Fri: ["6pm", "8pm"],
    Sat: ["10am", "12pm", "2pm", "4pm", "6pm"],
    Sun: ["12pm", "2pm"],
  };

  return (
    <div className="pt-20 min-h-screen">
      <InquiryModal open={modalOpen} onClose={() => setModalOpen(false)} companionName={c.name} />

      {lightboxOpen && (
        <div className="fixed inset-0 z-50 bg-black/95">
          <button
            onClick={closeLightbox}
            aria-label="Close image viewer"
            className="absolute right-4 top-4 z-10 p-3 text-white transition-colors hover:text-primary"
          >
            <X size={24} />
          </button>
          <button
            onClick={() => setImageZoomed((zoomed) => !zoomed)}
            aria-label={imageZoomed ? "Zoom out" : "Zoom in"}
            className="absolute right-16 top-4 z-10 p-3 text-white transition-colors hover:text-primary"
          >
            {imageZoomed ? <ZoomOut size={24} /> : <ZoomIn size={24} />}
          </button>
          {gallery.length > 1 && (
            <>
              <button
                onClick={showPrevImage}
                aria-label="Previous image"
                className="absolute left-4 top-1/2 z-10 -translate-y-1/2 p-3 text-white transition-colors hover:text-primary"
              >
                <ChevronLeft size={34} />
              </button>
              <button
                onClick={showNextImage}
                aria-label="Next image"
                className="absolute right-4 top-1/2 z-10 -translate-y-1/2 p-3 text-white transition-colors hover:text-primary"
              >
                <ChevronRight size={34} />
              </button>
            </>
          )}
          <div className="flex h-full w-full items-center justify-center overflow-auto p-6 sm:p-10">
            <button
              onClick={() => setImageZoomed((zoomed) => !zoomed)}
              className="min-h-full min-w-full cursor-zoom-in"
              aria-label={imageZoomed ? "Zoom out image" : "Zoom in image"}
            >
              <img
                src={gallery[currentImageIndex]}
                alt={`${c.name} enlarged image ${currentImageIndex + 1}`}
                className={`mx-auto transition-transform duration-300 ${
                  imageZoomed ? "max-w-none scale-125 cursor-zoom-out" : "max-h-[88vh] max-w-full cursor-zoom-in object-contain"
                }`}
              />
            </button>
          </div>
          <div className="absolute bottom-4 left-1/2 -translate-x-1/2 bg-black/70 px-3 py-1 text-xs text-white">
            {currentImageIndex + 1} / {gallery.length}
          </div>
        </div>
      )}

      {/* Info Header */}
      <div className={`relative flex min-h-[calc(100vh-5rem)] bg-gradient-to-b ${grad} py-8 lg:py-10`}>
        <div className="mx-auto flex w-full max-w-7xl px-6 lg:px-8">
          <div className="relative w-full">
            <div className="absolute top-6 left-6">
              <Link href="/companions">
                <span className="flex items-center gap-2 text-xs tracking-wider uppercase text-muted-foreground hover:text-primary transition-colors cursor-pointer">
                  <ArrowLeft size={14} />
                  Back
                </span>
              </Link>
            </div>
            <div className="absolute top-6 right-6">
              <button onClick={() => setFav(v => !v)} className="p-2">
                <Heart size={20} fill={fav ? "hsl(var(--primary))" : "none"} className="text-primary" />
              </button>
            </div>
            <div className="grid min-h-[calc(100vh-10rem)] gap-10 pt-12 lg:grid-cols-[minmax(0,1.08fr)_minmax(360px,0.92fr)] lg:items-center">
              <div className="grid h-[72vh] min-h-[560px] grid-cols-6 grid-rows-6 gap-3 border border-white/10 bg-black/20 p-3 lg:h-[calc(100vh-10rem)]">
                {collageImages.slice(0, 6).map((img, idx) => {
                  const tileClasses = [
                    "col-span-4 row-span-4",
                    "col-span-2 row-span-2",
                    "col-span-2 row-span-2",
                    "col-span-2 row-span-3",
                    "col-span-2 row-span-3",
                    "col-span-2 row-span-2",
                  ];
                  const galleryIndex = idx % gallery.length;

                  return (
                    <button
                      key={`${img}-${idx}`}
                      onClick={() => openLightbox(galleryIndex)}
                      aria-label={`Open image ${galleryIndex + 1}`}
                      className={`group relative overflow-hidden border transition-colors ${tileClasses[idx]} ${
                        galleryIndex === currentImageIndex ? "border-primary" : "border-white/15 hover:border-primary/60"
                      }`}
                    >
                      <img src={img} alt={`${c.name} collage image ${idx + 1}`} className="h-full w-full object-cover transition-transform duration-500 group-hover:scale-105" />
                      {galleryIndex === currentImageIndex && <span className="absolute bottom-2 right-2 bg-black/60 px-2 py-0.5 text-[10px] text-white">{galleryIndex + 1}</span>}
                    </button>
                  );
                })}
              </div>

              <div className="space-y-8">
                <div>
                  <div className="mb-3 flex items-center gap-2">
                    <span className="w-2 h-2 rounded-full" style={{ backgroundColor: c.availability === "Online" ? "#4ade80" : "#6b7280" }} />
                    <span className="text-sm text-white/70">{c.availability}</span>
                  </div>
                  <h1 className="mb-3 font-serif text-5xl text-foreground lg:text-6xl">{c.name}</h1>
                  <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-base text-muted-foreground">
                    <span className="flex items-center gap-1"><MapPin size={14} />{c.city}</span>
                    <span>Age {c.age}</span>
                    <span className="flex items-center gap-1"><Star size={14} fill="hsl(var(--primary))" className="text-primary" />{c.rating} ({c.reviews} reviews)</span>
                  </div>
                </div>

                <div className="border-y border-white/10 py-6">
                  <span className="mb-3 block text-xs tracking-[0.25em] uppercase text-primary">About</span>
                  <p className="text-base leading-8 text-muted-foreground">{c.bio}</p>
                </div>

                <div className="border border-white/10 bg-black/20 p-6">
                  <p className="text-xs tracking-wider uppercase text-muted-foreground mb-1">Starting from</p>
                  <p className="font-serif text-3xl text-primary mb-6">{c.pricing}</p>
                  <button
                    onClick={() => setModalOpen(true)}
                    className="w-full py-4 bg-primary text-background text-xs tracking-[0.25em] uppercase hover:bg-primary/90 transition-colors mb-3"
                  >
                    Booking Inquiry
                  </button>
                  <p className="text-[10px] text-muted-foreground text-center leading-relaxed">
                    Our concierge team will respond to your inquiry within 24 hours with complete discretion.
                  </p>
                </div>

                <div className="grid grid-cols-2 gap-3 text-xs sm:grid-cols-4 lg:grid-cols-2">
                  <div className="border border-white/10 p-4">
                    <p className="text-muted-foreground">City</p>
                    <p className="mt-1 text-foreground">{c.city}</p>
                  </div>
                  <div className="border border-white/10 p-4">
                    <p className="text-muted-foreground">Status</p>
                    <p className="mt-1 text-foreground">{c.availability}</p>
                  </div>
                  <div className="border border-white/10 p-4">
                    <p className="text-muted-foreground">Reviews</p>
                    <p className="mt-1 text-foreground">{c.reviews} verified</p>
                  </div>
                  <div className="border border-white/10 p-4">
                    <p className="text-muted-foreground">Rating</p>
                    <p className="mt-1 flex items-center gap-1 text-foreground">
                      <Star size={10} fill="hsl(var(--primary))" className="text-primary" />
                      {c.rating}
                    </p>
                  </div>
                </div>
            </div>
          </div>
          </div>
        </div>
      </div>

      {/* Content */}
      <div className="mx-auto w-full max-w-7xl space-y-12 px-6 py-16 lg:px-8">
        <div className="grid gap-10 lg:grid-cols-3">
          {/* Interests */}
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.6, delay: 0.1 }}>
            <span className="text-xs tracking-[0.25em] uppercase text-primary mb-3 block">Interests</span>
            <h2 className="font-serif text-2xl text-foreground mb-4">Interests & Passions</h2>
            <div className="flex flex-wrap gap-2">
              {c.interests.map(i => (
                <span key={i} className="px-4 py-1.5 border border-primary/30 text-sm text-primary/80">{i}</span>
              ))}
            </div>
          </motion.div>

          {/* Activities */}
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.6, delay: 0.15 }}>
            <span className="text-xs tracking-[0.25em] uppercase text-primary mb-3 block">Activities</span>
            <h2 className="font-serif text-2xl text-foreground mb-4">Preferred Activities</h2>
            <ul className="space-y-2">
              {c.activities.map(a => (
                <li key={a} className="flex items-center gap-3 text-sm text-muted-foreground">
                  <Activity size={12} className="text-primary shrink-0" />
                  {a}
                </li>
              ))}
            </ul>
          </motion.div>

          {/* Languages */}
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.6, delay: 0.2 }}>
            <span className="text-xs tracking-[0.25em] uppercase text-primary mb-3 block">Languages</span>
            <h2 className="font-serif text-2xl text-foreground mb-4">Languages Spoken</h2>
            <div className="flex flex-wrap gap-2">
              {c.languages.map(l => (
                <span key={l} className="flex items-center gap-1.5 px-3 py-1.5 bg-muted border border-border text-sm text-foreground">
                  <Languages size={12} className="text-primary" />
                  {l}
                </span>
              ))}
            </div>
          </motion.div>
        </div>

        <div className="grid gap-12 lg:grid-cols-[minmax(0,1fr)_minmax(420px,0.8fr)]">
          {/* Reviews */}
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.6, delay: 0.25 }}>
            <span className="text-xs tracking-[0.25em] uppercase text-primary mb-3 block">Reviews</span>
            <h2 className="font-serif text-2xl text-foreground mb-6">Client Reviews</h2>
            <div className="space-y-4">
              {[
                { author: "Anonymous Client", role: "Corporate Executive", content: "An exceptional evening. Poised, intelligent, and utterly charming.", rating: 5 },
                { author: "A. Sharma", role: "Private Investor", content: "Made the entire gala experience effortless. Would book again without hesitation.", rating: 5 },
              ].map((r, i) => (
                <div key={i} className="p-6 border border-border">
                  <div className="flex gap-0.5 mb-3">
                    {Array.from({ length: r.rating }).map((_, j) => <Star key={j} size={11} fill="hsl(var(--primary))" className="text-primary" />)}
                  </div>
                  <p className="text-sm text-muted-foreground italic mb-4">"{r.content}"</p>
                  <div className="flex items-center justify-between">
                    <div>
                      <p className="text-xs text-foreground">{r.author}</p>
                      <p className="text-[10px] text-muted-foreground">{r.role}</p>
                    </div>
                    <span className="text-[10px] border border-primary/20 text-primary/50 px-2 py-0.5">Verified Booking</span>
                  </div>
                </div>
              ))}
            </div>
          </motion.div>

          {/* Calendar */}
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.6, delay: 0.3 }}>
            <span className="text-xs tracking-[0.25em] uppercase text-primary mb-3 block">Availability</span>
            <h2 className="font-serif text-2xl text-foreground mb-6">This Week's Availability</h2>
            <div className="overflow-x-auto">
              <table className="w-full text-xs border-collapse">
                <thead>
                  <tr>
                    <th className="text-left p-2 text-muted-foreground font-normal border-b border-border w-16">Time</th>
                    {DAYS.map(d => (
                      <th key={d} className="p-2 text-muted-foreground font-normal border-b border-border text-center">{d}</th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {HOURS.map(h => (
                    <tr key={h}>
                      <td className="p-2 text-muted-foreground border-b border-border/50">{h}</td>
                      {DAYS.map(d => {
                        const avail = (availability[d] || []).includes(h);
                        return (
                          <td key={d} className="p-2 text-center border-b border-border/50">
                            <div className={`w-2 h-2 rounded-full mx-auto ${avail ? "bg-primary" : "bg-border"}`} />
                          </td>
                        );
                      })}
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
            <p className="text-[10px] text-muted-foreground mt-2">Gold = available. Contact us to confirm and reserve.</p>
          </motion.div>
        </div>
      </div>
    </div>
  );
}
