"use client";
import { useEffect } from "react";
import { useRouter } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import { Heart, MapPin, Clock, ShoppingBag } from "lucide-react";
import { timeAgo } from "./mockData";
import { useFormatPrice } from "@/hooks/useFormatPrice";
import { WishlistButton } from "./WishlistButton";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchWishlist } from "@/store/slices/marketplaceWishlistSlice";
import { mapApiToListing } from "@/utils/marketplace";

export function WishlistPage() {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { listings: apiListings, isLoading } = useAppSelector(
    (s) => s.marketplaceWishlist,
  );

  /* Force-refresh every time the page is visited */
  useEffect(() => {
    dispatch(fetchWishlist(true));
  }, [dispatch]);

  const formatPrice = useFormatPrice();

  /* listings is already kept in sync by optimisticToggle (removes on heart-off) */
  const savedListings = apiListings.map(mapApiToListing);




  return (
    <div className="min-h-full" style={{ background: "var(--bg)" }}>
      {/* Header */}
      <div className="px-4 pt-5 pb-4">
        <div className="flex items-center gap-2 mb-1">
          <Heart
            size={20}
            className="fill-[#fc0000] text-[#fc0000]"
            strokeWidth={1.5}
          />
          <h1
            className="text-xl font-black"
            style={{ color: "var(--text-primary)" }}
          >
            Wishlist
          </h1>
        </div>
        <p className="text-xs" style={{ color: "var(--text-muted)" }}>
          {isLoading
            ? "Loading…"
            : `${savedListings.length} saved listing${savedListings.length !== 1 ? "s" : ""}`}
        </p>
      </div>

      <div className="px-4 pb-24">
        {/* Loading skeleton */}
        {isLoading && (
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3 animate-pulse">
            {Array.from({ length: 4 }).map((_, i) => (
              <div
                key={i}
                className="rounded-2xl overflow-hidden border"
                style={{
                  background: "var(--card)",
                  borderColor: "var(--border)",
                }}
              >
                <div
                  className="aspect-[4/3]"
                  style={{ background: "var(--deep)" }}
                />
                <div className="p-2.5 space-y-2">
                  <div
                    className="h-3 w-3/4 rounded"
                    style={{ background: "var(--deep)" }}
                  />
                  <div
                    className="h-3 w-1/2 rounded"
                    style={{ background: "var(--deep)" }}
                  />
                </div>
              </div>
            ))}
          </div>
        )}

        {!isLoading && (
          <AnimatePresence mode="wait">
            {savedListings.length === 0 ? (
              <motion.div
                key="empty"
                initial={{ opacity: 0, y: 24 }}
                animate={{ opacity: 1, y: 0 }}
                className="flex flex-col items-center justify-center py-24 text-center"
              >
                <motion.div
                  initial={{ scale: 0 }}
                  animate={{ scale: 1 }}
                  transition={{ delay: 0.1, type: "spring", stiffness: 260 }}
                  className="w-20 h-20 rounded-full flex items-center justify-center mb-5"
                  style={{ background: "rgba(252,0,0,0.1)" }}
                >
                  <Heart
                    size={36}
                    style={{ color: "var(--accent)" }}
                    strokeWidth={1.5}
                  />
                </motion.div>
                <h2
                  className="text-base font-bold mb-2"
                  style={{ color: "var(--text-primary)" }}
                >
                  Your wishlist is empty
                </h2>
                <p
                  className="text-sm mb-6 max-w-[240px]"
                  style={{ color: "var(--text-muted)" }}
                >
                  Tap the heart icon on any listing to save it here
                </p>
                <motion.button
                  whileTap={{ scale: 0.95 }}
                  onClick={() => router.push("/marketplace")}
                  className="flex items-center gap-2 px-6 py-3 rounded-full font-bold text-sm text-white"
                  style={{ background: "var(--accent)" }}
                >
                  <ShoppingBag size={15} />
                  Browse Listings
                </motion.button>
              </motion.div>
            ) : (
              <motion.div
                key="list"
                className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3"
              >
                <AnimatePresence>
                  {savedListings.map((listing, i) => (
                    <motion.div
                      key={listing.id}
                      initial={{ opacity: 0, scale: 0.92 }}
                      animate={{ opacity: 1, scale: 1 }}
                      exit={{ opacity: 0, scale: 0.88, y: -8 }}
                      transition={{ delay: i * 0.04 }}
                      layout
                      whileHover={{ y: -3 }}
                      onClick={() =>
                        router.push(`/marketplace/listing/${listing.slug}`)
                      }
                      className="rounded-2xl overflow-hidden cursor-pointer border"
                      style={{
                        background: "var(--card)",
                        borderColor: "var(--border)",
                      }}
                    >
                      {/* Image */}
                      <div className="relative aspect-[4/3] bg-[var(--deep)]">
                        <img
                          src={listing.images[0]}
                          alt={listing.title}
                          className="w-full h-full object-cover"
                        />
                        <div className="absolute top-2 right-2">
                          <WishlistButton
                            listingId={listing.id}
                            size={15}
                            className="w-7 h-7 rounded-full bg-black/50 backdrop-blur-sm"
                          />
                        </div>
                        <div className="absolute bottom-0 left-0 right-0 p-2 bg-gradient-to-t from-black/70 to-transparent">
                          <span className="text-white font-black text-sm">
                            {formatPrice(listing.price)}
                          </span>
                          {listing.originalPrice && (
                            <span className="text-white/60 text-[10px] line-through ml-1">
                              {formatPrice(listing.originalPrice)}
                            </span>
                          )}
                        </div>
                      </div>

                      {/* Info */}
                      <div className="p-2.5">
                        <p
                          className="text-xs font-semibold line-clamp-2 leading-tight mb-1.5"
                          style={{ color: "var(--text-primary)" }}
                        >
                          {listing.title}
                        </p>
                        <div
                          className="flex items-center gap-1 text-[10px] mb-1"
                          style={{ color: "var(--text-muted)" }}
                        >
                          <MapPin size={9} />
                          <span className="truncate">
                            {listing.area}, {listing.city}
                          </span>
                        </div>
                        <div
                          className="flex items-center justify-between text-[10px]"
                          style={{ color: "var(--text-muted)" }}
                        >
                          <span className="flex items-center gap-1">
                            <Clock size={9} />
                            {timeAgo(listing.postedAt)}
                          </span>
                          {listing.isNegotiable && (
                            <span
                              className="text-[9px] font-bold px-1.5 py-0.5 rounded-full"
                              style={{
                                background: "rgba(240,192,64,0.15)",
                                color: "var(--accent-gold)",
                              }}
                            >
                              Negotiable
                            </span>
                          )}
                        </div>
                      </div>
                    </motion.div>
                  ))}
                </AnimatePresence>
              </motion.div>
            )}
          </AnimatePresence>
        )}
      </div>
    </div>
  );
}
