"use client";
import React, { useState, useEffect, useMemo } from "react";
import { motion, AnimatePresence } from "framer-motion";
import {
  Plus,
  Search,
  Edit2,
  Trash2,
  Eye,
  TrendingUp,
  Package,
  X,
  CheckCircle2,
  PauseCircle,
  Archive,
  FileEdit,
  ShoppingBag,
  ChevronRight,
  BarChart2,
  AlertTriangle,
} from "lucide-react";
import { EmptyState } from "@/components/marketplace/common/EmptyState";
import { slugify } from "@/utils/marketplace";
import { useFormatPrice } from "@/hooks/useFormatPrice";
import type { ListingStatus } from "@/types/marketplace";
import type { ApiListing } from "@/types/marketplace";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchMyListings } from "@/store/slices/marketplaceMyListingsSlice";
import type { MyListingsStatusParam } from "@/store/slices/marketplaceMyListingsSlice";
import Cookies from "js-cookie";
import apiClient from "@/lib/axiosClient";
import { API_ENDPOINTS } from "@/lib/apiEndpoints";

interface SellerListingsManagerProps {
  onCreateListing: () => void;
  onEditListing: (slug: string) => void;
}

/* ─── Status config ──────────────────────────────────────────────────────── */
const STATUS_CONFIG: Record<
  ListingStatus,
  {
    label: string;
    color: string;
    bg: string;
    icon: React.ElementType;
    desc: string;
  }
> = {
  active: {
    label: "Active",
    color: "#22c55e",
    bg: "rgba(34,197,94,0.1)",
    icon: CheckCircle2,
    desc: "Visible to buyers",
  },
  paused: {
    label: "Paused",
    color: "#f59e0b",
    bg: "rgba(245,158,11,0.1)",
    icon: PauseCircle,
    desc: "Hidden from search",
  },
  draft: {
    label: "Draft",
    color: "#6b7280",
    bg: "rgba(107,114,128,0.1)",
    icon: FileEdit,
    desc: "Not published yet",
  },
  sold: {
    label: "Sold",
    color: "#6366f1",
    bg: "rgba(99,102,241,0.1)",
    icon: ShoppingBag,
    desc: "Marked as sold",
  },
  expired: {
    label: "Expired",
    color: "#ef4444",
    bg: "rgba(239,68,68,0.1)",
    icon: Archive,
    desc: "Listing expired",
  },
};

const CHANGEABLE_STATUSES: ListingStatus[] = [
  "active",
  "paused",
  "draft",
  "sold",
];
const STATUS_TABS: (ListingStatus | "all")[] = [
  "all",
  "active",
  "paused",
  "draft",
  "sold",
];

/* Map UI tab → API status param */
const TAB_TO_STATUS: Record<ListingStatus | "all", MyListingsStatusParam> = {
  all: "all",
  active: 1,
  paused: 3,
  draft: 0,
  sold: 2,
  expired: "all",
};

/* Map API numeric status → ListingStatus string */
function apiStatusToListing(s: number): ListingStatus {
  const m: Record<number, ListingStatus> = {
    0: "draft",
    1: "active",
    2: "sold",
    3: "paused",
  };
  return m[s] ?? "draft";
}

/* Map a raw ApiListing to the shape the UI needs */
function mapToRow(api: ApiListing) {
  return {
    id: String(api.id),
    slug: `${slugify(api.title)}-${api.id}`,
    title: api.title,
    description: api.description,
    price: api.price,
    condition: api.listing_condition === 1 ? "new" : "used",
    status: apiStatusToListing(api.status) as ListingStatus,
    category: api.category_name,
    image: api.image,
    views: api.total_view,
    wishlisted: api.total_wishlist,
    city: api.city,
    area: api.area,
    createdAt: api.created_at,
  };
}
type ListingRow = ReturnType<typeof mapToRow>;

/* ─── Status bottom sheet ────────────────────────────────────────────────── */
function StatusSheet({
  listing,
  onClose,
  onEdit,
  onDelete,
}: {
  listing: ListingRow;
  onClose: () => void;
  onEdit: (slug: string) => void;
  onDelete: (id: string) => void;
}) {
  const formatPrice = useFormatPrice();
  const [confirmDelete, setConfirmDelete] = useState(false);
  const cfg = STATUS_CONFIG[listing.status];

  return (
    <AnimatePresence>
      <motion.div
        className="fixed inset-0 z-50 flex items-end sm:items-center justify-center sm:p-4"
        style={{ background: "rgba(0,0,0,0.55)", backdropFilter: "blur(4px)" }}
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        exit={{ opacity: 0 }}
        onClick={onClose}
      >
        <motion.div
          className="w-full sm:max-w-md rounded-t-3xl sm:rounded-2xl overflow-hidden"
          style={{
            background: "var(--card)",
            border: "1px solid var(--border)",
          }}
          initial={{ y: "100%" }}
          animate={{ y: 0 }}
          exit={{ y: "100%" }}
          transition={{ type: "spring", stiffness: 340, damping: 32 }}
          onClick={(e) => e.stopPropagation()}
        >
          {/* Handle */}
          <div className="flex justify-center pt-3 pb-1 sm:hidden">
            <div
              className="w-9 h-1 rounded-full"
              style={{ background: "var(--border)" }}
            />
          </div>

          {/* Header */}
          <div
            className="flex items-center justify-between px-5 pt-4 pb-3"
            style={{ borderBottom: "1px solid var(--border)" }}
          >
            <p
              className="font-black text-sm"
              style={{ color: "var(--text-primary)" }}
            >
              Listing Details
            </p>
            <button
              onClick={onClose}
              style={{
                color: "var(--text-muted)",
                background: "none",
                border: "none",
                cursor: "pointer",
                padding: 4,
              }}
            >
              <X size={18} />
            </button>
          </div>

          {/* Listing preview */}
          <div
            className="flex items-center gap-3 px-5 py-4"
            style={{ borderBottom: "1px solid var(--border)" }}
          >
            <img
              src={listing.image}
              alt={listing.title}
              className="w-14 h-14 rounded-xl object-cover shrink-0 bg-[var(--deep)]"
            />
            <div className="flex-1 min-w-0">
              <p
                className="text-sm font-bold truncate"
                style={{ color: "var(--text-primary)" }}
              >
                {listing.title}
              </p>
              <div className="flex items-center gap-2 mt-1">
                <span
                  className="text-sm font-black"
                  style={{ color: "var(--accent)" }}
                >
                  {formatPrice(listing.price)}
                </span>
                <span
                  className="text-[10px] font-bold px-2 py-0.5 rounded-full flex items-center gap-1"
                  style={{ background: cfg.bg, color: cfg.color }}
                >
                  <cfg.icon size={9} />
                  {cfg.label}
                </span>
              </div>
              <div
                className="flex items-center gap-3 mt-0.5"
                style={{ color: "var(--text-muted)" }}
              >
                <span className="flex items-center gap-1 text-[10px]">
                  <Eye size={9} />
                  {listing.views} views
                </span>
                <span className="flex items-center gap-1 text-[10px]">
                  <TrendingUp size={9} />
                  {listing.wishlisted} saved
                </span>
              </div>
            </div>
          </div>

          {/* Current status badge */}
          <div
            className="px-5 py-4"
            style={{ borderBottom: "1px solid var(--border)" }}
          >
            <p
              className="text-xs font-bold uppercase tracking-wider mb-3"
              style={{ color: "var(--text-muted)" }}
            >
              Current Status
            </p>
            <div
              className="flex items-center gap-3 p-3 rounded-xl"
              style={{ background: cfg.bg, border: `1.5px solid ${cfg.color}` }}
            >
              <div
                className="w-8 h-8 rounded-lg flex items-center justify-center shrink-0"
                style={{ background: cfg.color }}
              >
                <cfg.icon size={14} color="#fff" />
              </div>
              <div>
                <p className="text-sm font-bold" style={{ color: cfg.color }}>
                  {cfg.label}
                </p>
                <p
                  className="text-[10px]"
                  style={{ color: "var(--text-muted)" }}
                >
                  {cfg.desc}
                </p>
              </div>
            </div>
          </div>

          {/* Actions */}
          {!confirmDelete ? (
            <div className="px-5 py-4 flex gap-2">
              <motion.button
                whileTap={{ scale: 0.97 }}
                onClick={() => {
                  onEdit(listing.slug);
                  onClose();
                }}
                className="flex-1 flex items-center justify-center gap-2 py-2.5 rounded-xl text-sm font-bold"
                style={{
                  background: "var(--accent)",
                  color: "#fff",
                  border: "none",
                  cursor: "pointer",
                }}
              >
                <Edit2 size={14} />
                Edit
              </motion.button>
              <motion.button
                whileTap={{ scale: 0.97 }}
                onClick={() => setConfirmDelete(true)}
                className="flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold"
                style={{
                  background: "rgba(239,68,68,0.1)",
                  border: "1px solid rgba(239,68,68,0.3)",
                  color: "#ef4444",
                  cursor: "pointer",
                }}
              >
                <Trash2 size={14} />
              </motion.button>
              <motion.button
                whileTap={{ scale: 0.97 }}
                onClick={onClose}
                className="flex items-center justify-center px-4 py-2.5 rounded-xl"
                style={{
                  background: "var(--bg)",
                  border: "1px solid var(--border)",
                  color: "var(--text-muted)",
                  cursor: "pointer",
                }}
              >
                <X size={14} />
              </motion.button>
            </div>
          ) : (
            <div className="px-5 py-4">
              <div
                className="flex items-start gap-3 p-3 rounded-xl mb-3"
                style={{
                  background: "rgba(239,68,68,0.08)",
                  border: "1px solid rgba(239,68,68,0.2)",
                }}
              >
                <AlertTriangle
                  size={16}
                  className="text-[#ef4444] shrink-0 mt-0.5"
                />
                <p className="text-xs text-[#ef4444]">
                  Are you sure? This listing will be permanently deleted.
                </p>
              </div>
              <div className="flex gap-2">
                <motion.button
                  whileTap={{ scale: 0.97 }}
                  onClick={() => {
                    onDelete(listing.id);
                    onClose();
                  }}
                  className="flex-1 py-2.5 rounded-xl text-sm font-bold text-white"
                  style={{
                    background: "#ef4444",
                    border: "none",
                    cursor: "pointer",
                  }}
                >
                  Yes, Delete
                </motion.button>
                <motion.button
                  whileTap={{ scale: 0.97 }}
                  onClick={() => setConfirmDelete(false)}
                  className="flex-1 py-2.5 rounded-xl text-sm font-bold"
                  style={{
                    background: "var(--bg)",
                    border: "1px solid var(--border)",
                    color: "var(--text-muted)",
                    cursor: "pointer",
                  }}
                >
                  Cancel
                </motion.button>
              </div>
            </div>
          )}
        </motion.div>
      </motion.div>
    </AnimatePresence>
  );
}

/* ─── Loading skeleton ───────────────────────────────────────────────────── */
function Skeleton() {
  return (
    <div className="space-y-3 animate-pulse">
      {Array.from({ length: 4 }).map((_, i) => (
        <div
          key={i}
          className="flex items-center gap-3 p-3 rounded-2xl"
          style={{
            background: "var(--card)",
            border: "1px solid var(--border)",
          }}
        >
          <div
            className="w-16 h-16 rounded-xl shrink-0"
            style={{ background: "var(--deep)" }}
          />
          <div className="flex-1 space-y-2">
            <div
              className="h-3.5 w-3/4 rounded"
              style={{ background: "var(--deep)" }}
            />
            <div
              className="h-3 w-1/2 rounded"
              style={{ background: "var(--deep)" }}
            />
            <div
              className="h-3 w-1/3 rounded"
              style={{ background: "var(--deep)" }}
            />
          </div>
        </div>
      ))}
    </div>
  );
}

/* ─── Main component ─────────────────────────────────────────────────────── */
export function SellerListingsManager({
  onCreateListing,
  onEditListing,
}: SellerListingsManagerProps) {
  const dispatch = useAppDispatch();
  const formatPrice = useFormatPrice();
  const {
    listings: apiListings,
    stats,
    isLoading,
    error,
  } = useAppSelector((s) => s.marketplaceMyListings);

  const [activeTab, setActiveTab] = useState<ListingStatus | "all">("all");
  const [search, setSearch] = useState("");
  const [selected, setSelected] = useState<ListingRow | null>(null);

  useEffect(() => {
    dispatch(fetchMyListings("all"));
  }, [dispatch]);

  const handleTabChange = (tab: ListingStatus | "all") => {
    setActiveTab(tab);
    dispatch(fetchMyListings(TAB_TO_STATUS[tab]));
  };

  const handleDeleteListing = async (id: string) => {
    const channelId = Cookies.get("channel_id") ?? "";
    try {
      await apiClient.post(API_ENDPOINTS.CLASSIFIED.DELETE_LISTING, {
        listing_id: Number(id),
        channel_id: channelId,
      });
    } catch {}
    dispatch(fetchMyListings(TAB_TO_STATUS[activeTab]));
  };

  const rows = useMemo(() => apiListings.map(mapToRow), [apiListings]);

  /* Only client-side search — status filtering is done by the API */
  const filtered = useMemo(
    () =>
      rows.filter(
        (l) => !search || l.title.toLowerCase().includes(search.toLowerCase()),
      ),
    [rows, search],
  );

  /* Tab counts come from the API stats (always accurate) */
  const tabCount: Record<string, number> = {
    all: stats.totalListings,
    active: stats.active,
    draft: stats.draft,
    sold: stats.sold,
    paused: stats.paused,
  };

  return (
    <div className="p-4 md:p-6 max-w-6xl mx-auto">
      {/* Header */}
      <div className="flex items-center justify-between mb-5">
        <div>
          <h1
            className="text-xl font-bold"
            style={{ color: "var(--text-primary)" }}
          >
            My Listings
          </h1>
          <p className="text-sm mt-0.5" style={{ color: "var(--text-muted)" }}>
            {isLoading
              ? "Loading…"
              : `${stats.totalListings} total · ${stats.active} active`}
          </p>
        </div>
        <button
          onClick={onCreateListing}
          className="flex items-center gap-2 px-4 py-2 rounded-xl text-sm font-bold text-white"
          style={{
            background: "var(--accent)",
            border: "none",
            cursor: "pointer",
          }}
        >
          <Plus size={16} />
          <span className="hidden sm:inline">New Listing</span>
          <span className="sm:hidden">New</span>
        </button>
      </div>

      {/* Stats strip */}
      {!isLoading && stats.totalListings > 0 && (
        <div className="grid grid-cols-3 gap-2 mb-5">
          {[
            {
              label: "Total Views",
              value: stats.views,
              icon: Eye,
              color: "#6366f1",
            },
            {
              label: "Active",
              value: stats.active,
              icon: CheckCircle2,
              color: "#22c55e",
            },
            {
              label: "Saved",
              value: rows.reduce((s, l) => s + l.wishlisted, 0),
              icon: TrendingUp,
              color: "#fc0000",
            },
          ].map(({ label, value, icon: Icon, color }) => (
            <div
              key={label}
              className="rounded-xl p-3 border text-center"
              style={{
                background: "var(--card)",
                borderColor: "var(--border)",
              }}
            >
              <div className="flex items-center justify-center gap-1 mb-1">
                <Icon size={12} style={{ color }} />
                <span
                  className="text-[10px] font-semibold"
                  style={{ color: "var(--text-muted)" }}
                >
                  {label}
                </span>
              </div>
              <p
                className="text-lg font-black"
                style={{ color: "var(--text-primary)" }}
              >
                {value}
              </p>
            </div>
          ))}
        </div>
      )}

      {/* Search */}
      <div
        className="flex items-center gap-2 px-3 py-2.5 rounded-xl mb-4"
        style={{ background: "var(--card)", border: "1px solid var(--border)" }}
      >
        <Search size={14} style={{ color: "var(--text-muted)" }} />
        <input
          value={search}
          onChange={(e) => setSearch(e.target.value)}
          placeholder="Search listings…"
          className="bg-transparent flex-1 text-sm outline-none"
          style={{ color: "var(--text-primary)" }}
        />
        {search && (
          <button
            onClick={() => setSearch("")}
            style={{
              color: "var(--text-muted)",
              background: "none",
              border: "none",
              cursor: "pointer",
            }}
          >
            <X size={14} />
          </button>
        )}
      </div>

      {/* Status tabs */}
      <div className="flex gap-2 overflow-x-auto no-scrollbar mb-5">
        {STATUS_TABS.map((tab) => {
          const active = activeTab === tab;
          const cfg = tab !== "all" ? STATUS_CONFIG[tab] : null;
          const count = tabCount[tab] ?? 0;
          return (
            <button
              key={tab}
              onClick={() => handleTabChange(tab)}
              className="flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap"
              style={{
                background: active
                  ? cfg
                    ? cfg.bg
                    : "var(--accent)"
                  : "var(--card)",
                color: active
                  ? cfg
                    ? cfg.color
                    : "#fff"
                  : "var(--text-muted)",
                border: `1px solid ${active ? (cfg ? cfg.color : "var(--accent)") : "var(--border)"}`,
                cursor: "pointer",
              }}
            >
              {tab === "all" ? "All" : STATUS_CONFIG[tab].label}
              <span
                className="px-1.5 py-0.5 rounded-full text-[9px] font-black"
                style={{
                  background: active ? "rgba(255,255,255,0.25)" : "var(--deep)",
                  color: active ? "inherit" : "var(--text-muted)",
                }}
              >
                {count}
              </span>
            </button>
          );
        })}
      </div>

      {/* Content */}
      {isLoading ? (
        <Skeleton />
      ) : error ? (
        <div className="text-center py-16">
          <BarChart2
            size={32}
            className="mx-auto mb-3 opacity-30"
            style={{ color: "var(--text-muted)" }}
          />
          <p
            className="text-sm font-semibold mb-1"
            style={{ color: "var(--text-primary)" }}
          >
            Failed to load
          </p>
          <p className="text-xs mb-4" style={{ color: "var(--text-muted)" }}>
            {error}
          </p>
          <button
            onClick={() => dispatch(fetchMyListings("all"))}
            className="px-4 py-2 rounded-xl text-sm font-bold text-white"
            style={{ background: "var(--accent)" }}
          >
            Retry
          </button>
        </div>
      ) : filtered.length === 0 ? (
        <EmptyState
          icon={Package}
          title={search ? "No results" : "No listings here"}
          description={
            search
              ? `No listings match "${search}"`
              : "Create your first listing to start selling."
          }
          action={
            !search
              ? { label: "Create Listing", onClick: onCreateListing }
              : undefined
          }
        />
      ) : (
        <div className="space-y-3">
          {filtered.map((listing) => {
            const cfg = STATUS_CONFIG[listing.status];
            return (
              <motion.div
                key={listing.id}
                whileHover={{ y: -1 }}
                onClick={() => setSelected(listing)}
                className="flex items-center gap-3 p-3 rounded-2xl cursor-pointer group"
                style={{
                  background: "var(--card)",
                  border: "1px solid var(--border)",
                  transition: "border-color 0.15s",
                }}
                onMouseEnter={(e) => {
                  (e.currentTarget as HTMLElement).style.borderColor =
                    cfg.color + "50";
                }}
                onMouseLeave={(e) => {
                  (e.currentTarget as HTMLElement).style.borderColor =
                    "var(--border)";
                }}
              >
                {/* Image */}
                <div className="relative shrink-0">
                  <img
                    src={listing.image}
                    alt={listing.title}
                    className="w-16 h-16 rounded-xl object-cover bg-[var(--deep)]"
                  />
                  <span
                    className="absolute -top-1 -right-1 w-3.5 h-3.5 rounded-full border-2"
                    style={{
                      background: cfg.color,
                      borderColor: "var(--card)",
                    }}
                  />
                </div>

                {/* Details */}
                <div className="flex-1 min-w-0">
                  <p
                    className="text-sm font-semibold truncate"
                    style={{ color: "var(--text-primary)" }}
                  >
                    {listing.title}
                  </p>

                  <div className="flex items-center gap-2 mt-1 flex-wrap">
                    <span
                      className="text-[10px] font-bold px-2 py-0.5 rounded-full flex items-center gap-1"
                      style={{ background: cfg.bg, color: cfg.color }}
                    >
                      <cfg.icon size={9} />
                      {cfg.label}
                    </span>
                    <span
                      className="text-[10px]"
                      style={{ color: "var(--text-muted)" }}
                    >
                      {listing.area}, {listing.city}
                    </span>
                  </div>

                  <div className="flex items-center gap-3 mt-1.5">
                    <span
                      className="text-sm font-black"
                      style={{ color: "var(--accent)" }}
                    >
                      {formatPrice(listing.price)}
                    </span>
                    <span
                      className="flex items-center gap-1 text-[10px]"
                      style={{ color: "var(--text-muted)" }}
                    >
                      <Eye size={9} />
                      {listing.views}
                    </span>
                    <span
                      className="flex items-center gap-1 text-[10px]"
                      style={{ color: "var(--text-muted)" }}
                    >
                      <TrendingUp size={9} />
                      {listing.wishlisted}
                    </span>
                  </div>
                </div>

                {/* Tap hint */}
                <div
                  className="flex items-center gap-1 shrink-0"
                  style={{ color: "var(--text-muted)" }}
                >
                  <span className="text-[10px] hidden sm:block opacity-0 group-hover:opacity-100 transition-opacity">
                    Manage
                  </span>
                  <ChevronRight
                    size={16}
                    className="opacity-40 group-hover:opacity-100 transition-opacity"
                  />
                </div>
              </motion.div>
            );
          })}
        </div>
      )}

      {/* Status management sheet */}
      {selected && (
        <StatusSheet
          listing={selected}
          onClose={() => setSelected(null)}
          onEdit={onEditListing}
          onDelete={handleDeleteListing}
        />
      )}

      <style>{`
        .no-scrollbar::-webkit-scrollbar { display: none; }
        .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
      `}</style>
    </div>
  );
}
