"use client";
import { useState, useMemo, useEffect, useCallback } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import {
  Search,
  X,
  SlidersHorizontal,
  Grid,
  List,
  MapPin,
  Eye,
  Clock,
  ChevronDown,
  TrendingUp,
  History,
} from "lucide-react";
import { CONDITION_LABELS, timeAgo, type BuyerListing } from "./mockData";
import { useFormatPrice } from "@/hooks/useFormatPrice";
import { WishlistButton } from "./WishlistButton";
import { FilterPanel, type FilterState, DEFAULT_FILTERS } from "./FilterPanel";
import { useAppSelector, useAppDispatch } from "@/store/hooks";
import {
  fetchListings,
  type FetchListingsParams,
} from "@/store/slices/marketplaceListingsSlice";
import { mapApiToListing } from "@/utils/marketplace";

const TRENDING = [
  "iPhone 14",
  "MacBook Air M2",
  "PlayStation 5",
  "Royal Enfield",
  "DSLR Camera",
];
const SORT_OPTIONS = [
  { value: "latest", label: "Latest" },
  { value: "price_low", label: "Price ↑" },
  { value: "price_high", label: "Price ↓" },
  { value: "most_viewed", label: "Popular" },
];

function GridCard({ listing }: { listing: BuyerListing }) {
  const router = useRouter();
  const formatPrice = useFormatPrice();

  return (
    <motion.div
      layout
      whileHover={{ y: -2 }}
      onClick={() => router.push(`/marketplace/listing/${listing.slug}`)}
      className="rounded-2xl overflow-hidden cursor-pointer border"
      style={{ background: "var(--card)", borderColor: "var(--border)" }}
    >
      <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>
        </div>
      </div>
      <div className="p-2.5">
        <p
          className="text-xs font-semibold line-clamp-2 mb-1"
          style={{ color: "var(--text-primary)" }}
        >
          {listing.title}
        </p>
        <div
          className="flex items-center justify-between text-[10px]"
          style={{ color: "var(--text-muted)" }}
        >
          <span className="flex items-center gap-1 truncate">
            <MapPin size={9} />
            {listing.city}
          </span>
          <span className="flex items-center gap-1">
            <Clock size={9} />
            {timeAgo(listing.postedAt)}
          </span>
        </div>
      </div>
    </motion.div>
  );
}

function ListCard({ listing }: { listing: BuyerListing }) {
  const router = useRouter();
  const formatPrice = useFormatPrice();
  return (
    <motion.div
      layout
      whileHover={{ x: 2 }}
      onClick={() => router.push(`/marketplace/listing/${listing.slug}`)}
      className="flex gap-3 rounded-2xl overflow-hidden cursor-pointer border p-3"
      style={{ background: "var(--card)", borderColor: "var(--border)" }}
    >
      <div className="relative w-24 h-24 rounded-xl overflow-hidden shrink-0 bg-[var(--deep)]">
        <img
          src={listing.images[0]}
          alt={listing.title}
          className="w-full h-full object-cover"
        />
        <WishlistButton
          listingId={listing.id}
          size={13}
          className="absolute top-1 right-1 w-6 h-6 rounded-full bg-black/50"
        />
      </div>
      <div className="flex-1 min-w-0">
        <p
          className="text-sm font-semibold line-clamp-2 leading-snug mb-1"
          style={{ color: "var(--text-primary)" }}
        >
          {listing.title}
        </p>
        <p
          className="text-base font-black mb-1"
          style={{ color: "var(--accent)" }}
        >
          {formatPrice(listing.price)}
          {listing.originalPrice && (
            <span
              className="text-xs font-normal line-through ml-2"
              style={{ color: "var(--text-muted)" }}
            >
              {formatPrice(listing.originalPrice)}
            </span>
          )}
        </p>
        <div
          className="flex items-center gap-3 text-[11px]"
          style={{ color: "var(--text-muted)" }}
        >
          <span className="flex items-center gap-1">
            <MapPin size={10} />
            {listing.area}, {listing.city}
          </span>
          <span
            className="px-1.5 py-0.5 rounded-full text-[10px] font-bold"
            style={{
              background: "var(--deep)",
              color:
                listing.condition === "new" ? "#22c55e" : "var(--text-muted)",
            }}
          >
            {CONDITION_LABELS[listing.condition]}
          </span>
        </div>
        <div
          className="flex items-center gap-3 mt-1.5 text-[10px]"
          style={{ color: "var(--text-muted)" }}
        >
          <span className="flex items-center gap-1">
            <Eye size={9} />
            {listing.views} views
          </span>
          <span className="flex items-center gap-1">
            <Clock size={9} />
            {timeAgo(listing.postedAt)}
          </span>
        </div>
      </div>
    </motion.div>
  );
}

export function SearchResults() {
  const router = useRouter();
  const params = useSearchParams();
  const dispatch = useAppDispatch();

  const {
    listings: rawListings,
    isLoading,
    totalRows,
  } = useAppSelector((s) => s.marketplaceListings);
  const { categories: apiCategories } = useAppSelector(
    (s) => s.marketplaceCategory,
  );

  const [q, setQ] = useState(params.get("q") ?? "");
  const [viewMode, setViewMode] = useState<"grid" | "list">("grid");
  const [sort, setSort] = useState("latest");
  const [showSortMenu, setShowSortMenu] = useState(false);
  const [filterOpen, setFilterOpen] = useState(false);
  const [filters, setFilters] = useState<FilterState>(DEFAULT_FILTERS);
  const [recentSearches, setRecentSearches] = useState<string[]>([]);
  const [focused, setFocused] = useState(false);

  useEffect(() => {
    try {
      const s = localStorage.getItem("doliplay-recent-searches");
      if (s) setRecentSearches(JSON.parse(s).slice(0, 5));
    } catch {}
  }, []);

  const addRecent = (term: string) => {
    setRecentSearches((prev) => {
      const next = [term, ...prev.filter((r) => r !== term)].slice(0, 5);
      try {
        localStorage.setItem("doliplay-recent-searches", JSON.stringify(next));
      } catch {}
      return next;
    });
  };

  const doSearch = (term: string) => {
    if (!term.trim()) return;
    setQ(term);
    setFocused(false);
    addRecent(term);
  };

  /* ── Fetch from API whenever q or filters change ────────────────────────── */
  const triggerFetch = useCallback(() => {
    const fetchParams: FetchListingsParams = {};
    if (q.trim()) fetchParams.search = q.trim();
    if (filters.priceMin) fetchParams.min_price = parseInt(filters.priceMin);
    if (filters.priceMax) fetchParams.max_price = parseInt(filters.priceMax);
    if (filters.condition)
      fetchParams.listing_condition = parseInt(filters.condition);
    if (filters.date) fetchParams.date = filters.date;
    if (filters.latitude) fetchParams.latitude = parseFloat(filters.latitude);
    if (filters.longitude)
      fetchParams.longitude = parseFloat(filters.longitude);
    dispatch(fetchListings(fetchParams));
  }, [q, filters, dispatch]);

  useEffect(() => {
    triggerFetch();
  }, [triggerFetch]);

  /* ── Client-side sort ───────────────────────────────────────────────────── */
  const results = useMemo(() => {
    const items = rawListings.map(mapApiToListing);
    if (sort === "price_low") items.sort((a, b) => a.price - b.price);
    else if (sort === "price_high") items.sort((a, b) => b.price - a.price);
    else if (sort === "most_viewed") items.sort((a, b) => b.views - a.views);
    else
      items.sort(
        (a, b) =>
          new Date(b.postedAt).getTime() - new Date(a.postedAt).getTime(),
      );
    return items;
  }, [rawListings, sort]);

  const showSuggestions = focused && !q;
  const currentSortLabel =
    SORT_OPTIONS.find((s) => s.value === sort)?.label ?? "Latest";
  const displayCount = isLoading ? totalRows : results.length;

  return (
    <div className="min-h-full" style={{ background: "var(--bg)" }}>
      {/* Search header */}
      <div
        className="sticky top-0 z-30 px-4 py-3 border-b"
        style={{ background: "var(--bg)", borderColor: "var(--border)" }}
      >
        <div className="flex items-center gap-2 max-w-2xl mx-auto">
          <button onClick={() => router.back()} className="shrink-0 p-2 -ml-1">
            <X size={20} style={{ color: "var(--text-muted)" }} />
          </button>
          <div
            className="flex-1 flex items-center gap-2.5 rounded-xl px-3 py-2.5 border"
            style={{ background: "var(--card)", borderColor: "var(--border)" }}
          >
            <Search
              size={16}
              style={{ color: "var(--text-muted)" }}
              className="shrink-0"
            />
            <input
              value={q}
              onChange={(e) => setQ(e.target.value)}
              onFocus={() => setFocused(true)}
              onBlur={() => setTimeout(() => setFocused(false), 150)}
              onKeyDown={(e) => e.key === "Enter" && doSearch(q)}
              placeholder="Search listings..."
              className="flex-1 bg-transparent text-sm outline-none"
              style={{ color: "var(--text-primary)" }}
              autoFocus
            />
            {q && (
              <button onClick={() => setQ("")}>
                <X size={14} style={{ color: "var(--text-muted)" }} />
              </button>
            )}
          </div>
        </div>

        {/* Suggestions dropdown */}
        <AnimatePresence>
          {showSuggestions && (
            <motion.div
              initial={{ opacity: 0, y: -8 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -8 }}
              className="absolute left-4 right-4 top-full mt-1 rounded-2xl border overflow-hidden z-40"
              style={{
                background: "var(--card)",
                borderColor: "var(--border)",
              }}
            >
              {recentSearches.length > 0 && (
                <div className="p-3">
                  <p
                    className="text-[10px] font-bold uppercase tracking-wider mb-2"
                    style={{ color: "var(--text-muted)" }}
                  >
                    Recent Searches
                  </p>
                  {recentSearches.map((r) => (
                    <button
                      key={r}
                      onClick={() => doSearch(r)}
                      className="flex items-center gap-2 w-full py-1.5 text-sm"
                      style={{ color: "var(--text-primary)" }}
                    >
                      <History
                        size={13}
                        style={{ color: "var(--text-muted)" }}
                      />
                      {r}
                    </button>
                  ))}
                </div>
              )}
              <div
                className="p-3 border-t"
                style={{ borderColor: "var(--border)" }}
              >
                <p
                  className="text-[10px] font-bold uppercase tracking-wider mb-2"
                  style={{ color: "var(--text-muted)" }}
                >
                  Trending
                </p>
                {TRENDING.map((t) => (
                  <button
                    key={t}
                    onClick={() => doSearch(t)}
                    className="flex items-center gap-2 w-full py-1.5 text-sm"
                    style={{ color: "var(--text-primary)" }}
                  >
                    <TrendingUp size={13} style={{ color: "var(--accent)" }} />
                    {t}
                  </button>
                ))}
              </div>
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      {/* Toolbar */}
      <div
        className="flex items-center gap-2 px-4 py-2.5 border-b"
        style={{ borderColor: "var(--border)" }}
      >
        <span className="text-xs flex-1" style={{ color: "var(--text-muted)" }}>
          <span className="font-bold" style={{ color: "var(--text-primary)" }}>
            {displayCount}
          </span>{" "}
          results
          {q && (
            <>
              {" "}
              for{" "}
              <span
                className="font-semibold"
                style={{ color: "var(--accent)" }}
              >
                &ldquo;{q}&rdquo;
              </span>
            </>
          )}
        </span>

        {/* Sort */}
        <div className="relative">
          <button
            onClick={() => setShowSortMenu((p) => !p)}
            className="flex items-center gap-1 text-xs font-semibold px-3 py-1.5 rounded-full border"
            style={{
              borderColor: "var(--border)",
              background: "var(--card)",
              color: "var(--text-primary)",
            }}
          >
            {currentSortLabel}
            <ChevronDown size={12} />
          </button>
          <AnimatePresence>
            {showSortMenu && (
              <motion.div
                initial={{ opacity: 0, scale: 0.95, y: -4 }}
                animate={{ opacity: 1, scale: 1, y: 0 }}
                exit={{ opacity: 0, scale: 0.95 }}
                className="absolute right-0 top-8 z-50 rounded-xl border overflow-hidden min-w-[150px]"
                style={{
                  background: "var(--card)",
                  borderColor: "var(--border)",
                }}
              >
                {SORT_OPTIONS.map((opt) => (
                  <button
                    key={opt.value}
                    onClick={() => {
                      setSort(opt.value);
                      setShowSortMenu(false);
                    }}
                    className="flex items-center justify-between w-full px-4 py-2.5 text-sm"
                    style={{
                      color:
                        sort === opt.value
                          ? "var(--accent)"
                          : "var(--text-primary)",
                      background:
                        sort === opt.value
                          ? "rgba(252,0,0,0.08)"
                          : "transparent",
                    }}
                  >
                    {opt.label}
                  </button>
                ))}
              </motion.div>
            )}
          </AnimatePresence>
        </div>

        {/* Filter button */}
        <button
          onClick={() => setFilterOpen(true)}
          className="flex items-center justify-center w-8 h-8 rounded-full border"
          style={{ borderColor: "var(--border)", background: "var(--card)" }}
        >
          <SlidersHorizontal size={14} style={{ color: "var(--text-muted)" }} />
        </button>

        {/* View toggle */}
        <div
          className="flex rounded-lg overflow-hidden border"
          style={{ borderColor: "var(--border)" }}
        >
          <button
            onClick={() => setViewMode("grid")}
            className="p-1.5 transition-colors"
            style={{
              background: viewMode === "grid" ? "var(--accent)" : "var(--card)",
              color: viewMode === "grid" ? "white" : "var(--text-muted)",
            }}
          >
            <Grid size={14} />
          </button>
          <button
            onClick={() => setViewMode("list")}
            className="p-1.5 transition-colors"
            style={{
              background: viewMode === "list" ? "var(--accent)" : "var(--card)",
              color: viewMode === "list" ? "white" : "var(--text-muted)",
            }}
          >
            <List size={14} />
          </button>
        </div>
      </div>

      {/* Results */}
      <div className="p-4 pb-24">
        <AnimatePresence mode="wait">
          {isLoading ? (
            <motion.div
              key="loading"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3"
            >
              {Array.from({ length: 8 }).map((_, i) => (
                <div
                  key={i}
                  className="rounded-2xl overflow-hidden border animate-pulse"
                  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 rounded"
                      style={{ background: "var(--deep)", width: "80%" }}
                    />
                    <div
                      className="h-3 rounded"
                      style={{ background: "var(--deep)", width: "50%" }}
                    />
                  </div>
                </div>
              ))}
            </motion.div>
          ) : results.length === 0 ? (
            <motion.div
              key="empty"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              className="flex flex-col items-center justify-center py-20 text-center"
            >
              <div className="text-5xl mb-4">🔍</div>
              <h3
                className="text-base font-bold mb-1"
                style={{ color: "var(--text-primary)" }}
              >
                No results found
              </h3>
              <p className="text-sm" style={{ color: "var(--text-muted)" }}>
                Try a different search or clear your filters
              </p>
            </motion.div>
          ) : viewMode === "grid" ? (
            <motion.div
              key="grid"
              className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3"
            >
              {results.map((l, i) => (
                <motion.div
                  key={l.id}
                  initial={{ opacity: 0, y: 12 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ delay: i * 0.04 }}
                >
                  <GridCard listing={l} />
                </motion.div>
              ))}
            </motion.div>
          ) : (
            <motion.div key="list" className="flex flex-col gap-3">
              {results.map((l, i) => (
                <motion.div
                  key={l.id}
                  initial={{ opacity: 0, x: -12 }}
                  animate={{ opacity: 1, x: 0 }}
                  transition={{ delay: i * 0.04 }}
                >
                  <ListCard listing={l} />
                </motion.div>
              ))}
            </motion.div>
          )}
        </AnimatePresence>
      </div>

      <FilterPanel
        open={filterOpen}
        onClose={() => setFilterOpen(false)}
        filters={filters}
        onApply={(f) => setFilters(f)}
        resultCount={results.length}
      />
    </div>
  );
}
