import React, { useEffect, useState } from "react";
import Image from "next/image";

import { saveTrade, updateTradePrice } from "@/app/lib/api/list";
import { User } from "@/constants/types";
import { useSelector } from "react-redux";

export type ChildTabs = "magic" | "pokemon" | "lorcana" | "listing";

export type TradeCardItem = {
  id: number;
  player: string;
  timeAgo: string;
  rarity: string;
  name: string;
  price: string; // "$11.90"
  image: string;
  inventory?: number;
  brand: string; // ⬅️ IMPORTANT
};

export type CartItem = TradeCardItem & { tab: ChildTabs };

type CartSidebarProps = {
  items: CartItem[];
  onList?: (item: CartItem, quantity: number) => void;
  handler?: (item: CartItem) => void; // row click (select, etc.)
  onPriceChange?: (item: CartItem, newPrice: number) => void;
  totalItems: number;
  totalCost: number;
  open: boolean;
  onClose: () => void;
  loadCardsHandler: () => void;
  onClearCart?: () => void;
  showListButton?: boolean; // 🔹 NEW
  showEditBitton?: boolean;
  setListingReloadToken?: boolean;
};

type AnimatedCartItem = CartItem & {
  animationClass?: string;
};

const ListSidebar = ({
  items,
  handler,
  onList,
  onPriceChange,
  totalItems,
  totalCost,
  open,
  onClose,
  loadCardsHandler,
  onClearCart,
  showListButton = true,
  showEditBitton = true,
}: CartSidebarProps) => {
  const [renderedItems, setRenderedItems] = useState<AnimatedCartItem[]>([]);
  const [selectedId, setSelectedId] = useState<number | null>(null);
  const [quantities, setQuantities] = useState<Record<number, number>>({});
  const [editingPriceId, setEditingPriceId] = useState<number | null>(null);
  const [priceDrafts, setPriceDrafts] = useState<Record<number, string>>({});
  const [saving, setSaving] = useState(false);
  const [modalOpen, setModalOpen] = useState(false);
  const [modalMsg, setModalMsg] = useState("");
  const [modalType, setModalType] = useState<"success" | "error" | null>(null);
  const user = useSelector((state: any) => state.auth.user) as User | null;

  const handleListAll = async () => {
    if (items.length < 1 || saving) return;
    if (!user) return;
    try {
      setSaving(true);

      const payload = {
        user_id: user.userId,
        cards: items.map((item) => {
          const raw =
            priceDrafts[item.id] != null
              ? priceDrafts[item.id]
              : stripDollar(item.price);

          const priceNum = Number(raw);
          return {
            inv_id: item.id,
            price: isNaN(priceNum) ? 0 : priceNum,
          };
        }),
        token:user.token
      };

      const data = await saveTrade(payload);

      if (data.resp === "success") {
        // ✅ show success modal
        setModalType("success");
        setModalMsg(data.msg || "Cards listed successfully.");
        setModalOpen(true);

        // ✅ RESET cart after success
        onClearCart?.(); // clears sidebar cart
        setQuantities({}); // resets qty fields
        setPriceDrafts({}); // clears price inputs
        setSelectedId(null); // close expanded item
        // onClose?.();
      } else {
        // ❌ API responded with error
        setModalType("error");
        setModalMsg(data.msg || "Failed to list cards.");
        setModalOpen(true);
      }
    } catch (err) {
      console.error("Failed to save trade", err);
      setModalType("error");
      setModalMsg("Something went wrong while listing cards.");
      setModalOpen(true);
    } finally {
      setSaving(false);
      loadCardsHandler(); // reload updated inventory
    }
  };

  const stripDollar = (price: string) =>
    price.trim().startsWith("$") ? price.trim().slice(1) : price.trim();

  // sync items + animation + initial qty/price drafts
  useEffect(() => {
    setRenderedItems((prev) => {
      const next: AnimatedCartItem[] = [];
      const newIds = new Set(items.map((i) => i.id));

      items.forEach((item) => {
        const existing = prev.find((p) => p.id === item.id);
        if (existing) {
          next.push({ ...item, animationClass: existing.animationClass });
        } else {
          next.push({ ...item, animationClass: "cart-item-enter" });
        }
      });

      prev.forEach((oldItem) => {
        if (!newIds.has(oldItem.id)) {
          if (oldItem.animationClass !== "cart-item-exit") {
            const exitingItem = {
              ...oldItem,
              animationClass: "cart-item-exit",
            };
            next.push(exitingItem);

            setTimeout(() => {
              setRenderedItems((current) =>
                current.filter((c) => c.id !== oldItem.id)
              );
            }, 250);
          }
        }
      });

      return next;
    });

    // initialise quantities & price drafts
    setQuantities((prev) => {
      const copy = { ...prev };
      items.forEach((item) => {
        if (copy[item.id] == null) copy[item.id] = 0;
      });
      return copy;
    });

    setPriceDrafts((prev) => {
      const copy = { ...prev };
      items.forEach((item) => {
        if (copy[item.id] == null) {
          copy[item.id] = stripDollar(item.price);
        }
      });
      return copy;
    });
  }, [items]);

  const handleRowClick = (item: CartItem) => {
    setSelectedId((prev) => (prev === item.id ? null : item.id));
    // handler?.(item);
  };

  const handleChangeQty = (id: number, value: string) => {
    const num = Number(value.replace(/\D/g, ""));
    setQuantities((prev) => ({
      ...prev,
      [id]: isNaN(num) ? 0 : num,
    }));
  };

  const handleListClick = (item: CartItem) => {
    const qty = quantities[item.id] ?? 0;
    if (onList) onList(item, qty);
  };

  const handlePriceDraftChange = (id: number, value: string) => {
    // allow numbers + decimal point
    const sanitized = value.replace(/[^0-9.]/g, "");
    setPriceDrafts((prev) => ({
      ...prev,
      [id]: sanitized,
    }));
  };

  const commitPrice = async (item: CartItem) => {
    if (!user) return;
    const raw = priceDrafts[item.id];
    const num = Number(raw);

    if (isNaN(num)) {
      setEditingPriceId(null);
      return;
    }

    try {
      // 🔹 API call: /api/update-trade
      const res = await updateTradePrice({
        user_id: user.userId,
        id: item.id,
        prices: num,
        brand: item.brand,
        token:user.token
      });
      if (res.resp === "success") {
        if (onPriceChange) {
          onPriceChange(item, num);
        }
        onClearCart?.();
        setModalType("success");
        setModalMsg(res.msg || "Price Updated Successfuly");
      } else {
        setModalType("error");
        setModalMsg(res.msg || "Failed to update price");
      }
    } catch (err) {
      console.error("Failed to update price", err);
      setModalType("error");
      setModalMsg("Something went wrong while updating price.");
    } finally {
      setEditingPriceId(null);
      setModalOpen(true);
    }
  };

  return (
    <>
      {modalOpen && (
        <div className="fixed inset-0 z-[10000] flex items-center justify-center bg-black/60">
          <div className="bg-[var(--color-naviBlue)] px-6 py-4 max-w-sm w-full">
            <h3 className="text-sm md:text-xl text-center font-sofia font-extrabold mb-2">
              {modalType === "error" ? "Error" : "Success"}
            </h3>
            <p
              className={`text-sm md:text-xl text-center mb-4 ${
                modalType === "error" ? "text-red-400" : "text-green-400"
              }`}
            >
              {modalMsg}
            </p>
            <button
              onClick={() => setModalOpen(false)}
              className="w-full cursor-pointer py-2 text-sm md:text-base font-sofia font-extrabold bg-[var(--color-blue)]  hover:bg-[var(--color-hoverBlue)] duration-300"
            >
              OK
            </button>
          </div>
        </div>
      )}

      <div
        className={`
          fixed top-0 right-0 h-screen md:w-[276px]
          bg-[var(--color-naviBlue)] border-l border-[#151C29]
          shadow-xl z-[9999] 
          transform transition-transform duration-500 ease-in-out
          ${open ? "translate-x-0" : "translate-x-full"}
        `}
      >
        <div className="px-4 pt-4 pb-2">
          <h2 className="text-xs md:text-sm font-sofia font-extrabold ">
            LIST CARDS
          </h2>
        </div>

        <button
          className="absolute top-3 right-3 text-white text-xl font-bold"
          onClick={onClose}
        >
          ✕
        </button>

        <div className="flex-1 px-4 space-y-4 mt-3 2xl:max-h-[81vh] max-h-[71vh] overflow-y-auto nice-scrollbar">
          {renderedItems.map((item) => {
            const isSelected = selectedId === item.id;
            const qty = quantities[item.id] ?? 0;
            const inventory = item.inventory ?? 0;
            const isEditingPrice = editingPriceId === item.id;
            const priceDraft = priceDrafts[item.id] ?? stripDollar(item.price);

            return (
              <div
                key={item.id}
                className={`
                  border border-[#29313D] bg-[#161E2A]
                  px-3 py-3 flex flex-col gap-3
                  ${item.animationClass ?? ""}
                `}
              >
                {/* top row: image + title + price */}
                <button
                  type="button"
                  // onClick={() => handler?.(item)}
                  className="flex gap-3 cursor-pointer text-left w-full"
                >
                  <div className="w-16 h-20 shrink-0">
                    <Image
                      src={item.image}
                      alt={item.name}
                      width={64}
                      height={80}
                      className="w-full h-full object-cover"
                    />
                  </div>

                  <div className="flex-1 flex flex-col justify-between">
                    <div>
                      <p className="text-[11px] text-[#8F8F8F] font-sofia">
                        {item.rarity}
                      </p>
                      <p className="text-sm font-extrabold font-sofia uppercase leading-tight">
                        {item.name.split(" ").slice(0, 2).join(" ")}
                      </p>
                    </div>

                    {/* price pill */}
                    <div className="mt-3 w-fit flex items-center gap-2 bg-[#13151A] px-2 py-2 font-sofia">
                      <span className="text-xs text-[#DBFAFF] font-onest">
                        $
                      </span>

                      {isEditingPrice ? (
                        <input
                          autoFocus
                          value={priceDraft}
                          onChange={(e) =>
                            handlePriceDraftChange(item.id, e.target.value)
                          }
                          // onBlur={() => commitPrice(item)}
                          onKeyDown={(e) => {
                            if (e.key === "Enter") {
                              e.preventDefault();
                              commitPrice(item);
                            }
                            if (e.key === "Escape") {
                              setEditingPriceId(null);
                            }
                          }}
                          className="w-14 bg-transparent border-b border-[#6366F1] text-sm text-[#DBFAFF] font-extrabold outline-none"
                        />
                      ) : (
                        <span className="text-sm text-[#DBFAFF] font-extrabold">
                          {priceDraft}
                        </span>
                      )}

                      {isEditingPrice ? (
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            commitPrice(item);
                          }}
                          className="ml-2 text-[10px] px-2 py-1 bg-[#4D4CFE] rounded text-white font-sofia"
                        >
                          SAVE
                        </button>
                      ) : (
                        <>
                          {showEditBitton && (
                            <button
                              type="button"
                              onClick={(e) => {
                                e.stopPropagation();
                                handleRowClick(item);
                                setEditingPriceId(item.id);
                              }}
                              className="ml-1"
                            >
                              <img
                                src="/images/list/edit.svg"
                                className="w-4"
                                alt="edit price"
                              />
                            </button>
                          )}
                        </>
                      )}
                    </div>
                  </div>
                </button>

                {/* expanded controls */}
                {isSelected && (
                  <div className="pt-3 border-t border-[#29313D] flex items-center justify-between gap-3">
                    <p className="text-xs font-sofia">
                      {inventory} in inventory
                    </p>

                    {/* Quantity pill */}
                    <div className="flex items-center bg-[#1B2332] rounded-full px-3 py-1 gap-3">
                      {/* Minus button */}
                      <button
                        type="button"
                        onClick={(e) => {
                          e.stopPropagation();
                          setQuantities((prev) => ({
                            ...prev,
                            [item.id]: Math.max(0, (prev[item.id] || 0) - 1),
                          }));
                        }}
                        className="text-lg font-sofia text-white px-1"
                      >
                        –
                      </button>

                      {/* Quantity */}
                      <div className="w-10 text-center bg-transparent text-sm font-sofia font-extrabold text-white outline-none">
                        {qty}
                      </div>

                      {/* Plus button */}
                      <button
                        type="button"
                        onClick={(e) => {
                          e.stopPropagation();
                          setQuantities((prev) => ({
                            ...prev,
                            [item.id]: (prev[item.id] || 0) + 1,
                          }));
                        }}
                        className="text-lg font-sofia text-white px-1"
                      >
                        +
                      </button>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>

        <div
          className={`${
            renderedItems.length < 1 ? "absolute top-1/2 " : ""
          }w-full px-4 mt-4`}
        >
          {/* <div className="px-4 py-3 text-xs md:text-sm font-sofia space-y-1">
            <div className="flex justify-between">
              <span>TOTAL ITEMS</span>
              <span>{totalItems}</span>
            </div>
            <div className="flex justify-between">
              <span>TOTAL VALUE</span>
              <span className="font-extrabold">${totalCost.toFixed(2)}</span>
            </div>
          </div> */}
          {renderedItems.length < 1 && (
            <h1 className="font-sofia text-center uppercase text-sm md:text-lg font-extrabold text-[#29313D]">
              Your listed cards will appear here
            </h1>
          )}
          {showListButton && (
            <button
              onClick={handleListAll}
              disabled={renderedItems.length < 1 || saving}
              className={`w-full mt-3 font-onest py-3 text-xs md:text-sm font-extrabold font-sofia tracking-wide ${
                renderedItems.length < 1 || saving
                  ? "bg-[#29313D] cursor-not-allowed"
                  : "bg-[#4D4CFE] hover:bg-[#4F46E5] cursor-pointer"
              }`}
            >
              {saving ? "LISTING..." : "LIST CARDS"}
            </button>
          )}
        </div>
      </div>
    </>
  );
};

export default ListSidebar;
