"use client";
import { useState, useEffect, useRef, useCallback } from "react";
import { X, Plus, Loader2 } from "lucide-react";
import { AnimatePresence, motion } from "framer-motion";
import { useRouter } from "next/navigation";
import { fetchGifts, sendGiftAPI } from "@/services/liveService";
import { useTranslation } from "@/i18n";
import type { Gift } from "@/types/live";

interface GiftSheetProps {
  isOpen: boolean;
  onClose: () => void;
  userId: number;
  walletBalance: number;
  hostChannelId: string;
  onGiftSent: (gift: Gift) => void;
}

export function GiftSheet({
  isOpen,
  onClose,
  userId,
  walletBalance,
  hostChannelId,
  onGiftSent,
}: GiftSheetProps) {
  const [gifts, setGifts] = useState<Gift[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isSending, setIsSending] = useState<number | null>(null);
  const [currentPage, setCurrentPage] = useState(0);
  const [totalPage, setTotalPage] = useState(0);
  const [hasMore, setHasMore] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);
  const { t } = useTranslation();
  const router = useRouter();

  const loadGifts = useCallback(async (page: number) => {
    setIsLoading(true);
    try {
      const res = await fetchGifts(userId, page);
      if (res.status === 200 && res.result) {
        setGifts(prev => {
          const merged = [...prev, ...res.result];
          const unique = Array.from(new Map(merged.map(g => [g.id, g])).values());
          return unique;
        });
        setCurrentPage(res.current_page);
        setTotalPage(res.total_page);
        setHasMore(res.more_page);
      }
    } catch (e) {
      console.error("Failed to load gifts", e);
    } finally {
      setIsLoading(false);
    }
  }, [userId]);

  useEffect(() => {
    if (isOpen && gifts.length === 0) {
      loadGifts(1);
    }
  }, [isOpen, gifts.length, loadGifts]);

  // Load more on scroll
  const handleScroll = useCallback(() => {
    if (!scrollRef.current) return;
    const { scrollTop, scrollHeight, clientHeight } = scrollRef.current;
    if (scrollHeight - scrollTop - clientHeight < 80 && hasMore && !isLoading) {
      loadGifts(currentPage + 1);
    }
  }, [hasMore, isLoading, currentPage, loadGifts]);

  const handleSendGift = async (gift: Gift) => {
    if (walletBalance < gift.price) {
      router.push("/wallet");
      onClose();
      return;
    }
    setIsSending(gift.id);
    try {
      const res = await sendGiftAPI({
        userId,
        giftId: gift.id,
        channelId: hostChannelId,
        price: gift.price,
      });
      if (res.status === 200) {
        onGiftSent(gift);
      }
    } catch (e) {
      console.error("Failed to send gift", e);
    } finally {
      setIsSending(null);
    }
  };

  const handleClose = () => {
    setGifts([]);
    setCurrentPage(0);
    onClose();
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <>
          {/* Backdrop */}
          <motion.div
            className="fixed inset-0 z-[500]"
            style={{ background: "rgba(0,0,0,0.6)", backdropFilter: "blur(4px)" }}
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            onClick={handleClose}
          />

          {/* Sheet */}
          <motion.div
            className="fixed left-0 right-0 bottom-0 z-[501] flex flex-col rounded-t-3xl overflow-hidden"
            style={{
              maxHeight: "70vh",
              background: "var(--card)",
              borderTop: "1px solid var(--border)",
            }}
            initial={{ y: "100%" }}
            animate={{ y: 0 }}
            exit={{ y: "100%" }}
            transition={{ type: "spring", stiffness: 280, damping: 30 }}
          >
            {/* Handle + Header */}
            <div className="flex-shrink-0 flex items-center justify-between px-5 pt-3 pb-2">
              <div
                className="absolute left-1/2 -translate-x-1/2 top-2 w-10 h-1 rounded-full"
                style={{ background: "var(--border)" }}
              />
              <p className="text-sm font-bold mt-1" style={{ color: "var(--text-primary)" }}>
                {t("live_gifts")}
              </p>
              <button
                onClick={handleClose}
                className="w-7 h-7 rounded-full flex items-center justify-center"
                style={{ background: "var(--deep)", color: "var(--text-muted)" }}
              >
                <X size={14} />
              </button>
            </div>

            {/* Gift grid */}
            <div
              ref={scrollRef}
              onScroll={handleScroll}
              className="flex-1 overflow-y-auto px-4 pb-4"
            >
              {isLoading && gifts.length === 0 ? (
                <div className="grid grid-cols-3 gap-3 pt-2">
                  {Array.from({ length: 6 }).map((_, i) => (
                    <div
                      key={i}
                      className="flex flex-col items-center gap-2 rounded-2xl p-3 animate-pulse"
                      style={{ background: "var(--deep)" }}
                    >
                      <div className="w-12 h-12 rounded-xl" style={{ background: "var(--card)" }} />
                      <div className="h-2.5 w-16 rounded-full" style={{ background: "var(--card)" }} />
                      <div className="h-7 w-full rounded-lg" style={{ background: "var(--card)" }} />
                    </div>
                  ))}
                </div>
              ) : gifts.length === 0 ? (
                <div className="flex items-center justify-center py-12 text-sm" style={{ color: "var(--text-muted)" }}>
                  {t("live_noGifts")}
                </div>
              ) : (
                <div className="grid grid-cols-3 gap-3 pt-2">
                  {gifts.map((gift) => (
                    <div
                      key={gift.id}
                      className="flex flex-col items-center gap-1.5 rounded-2xl p-3"
                      style={{ background: "var(--deep)", border: "1px solid var(--border-soft)" }}
                    >
                      {/* Gift image */}
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img
                        src={gift.image}
                        alt={gift.name}
                        className="w-12 h-12 object-contain"
                        onError={(e) => {
                          (e.target as HTMLImageElement).style.display = "none";
                        }}
                      />
                      {/* Price */}
                      <p className="text-[10px] font-semibold" style={{ color: "var(--text-muted)" }}>
                        🪙 {gift.price}
                      </p>
                      {/* Send button */}
                      <button
                        onClick={() => handleSendGift(gift)}
                        disabled={isSending === gift.id}
                        className="w-full h-7 rounded-lg text-[10px] font-black flex items-center justify-center transition-all active:scale-95"
                        style={{
                          background: walletBalance >= gift.price
                            ? "linear-gradient(135deg, var(--accent), var(--accent)cc)"
                            : "var(--card)",
                          color: walletBalance >= gift.price ? "#fff" : "var(--text-muted)",
                          border: walletBalance >= gift.price ? "none" : "1px solid var(--border)",
                        }}
                      >
                        {isSending === gift.id ? (
                          <Loader2 size={12} className="animate-spin" />
                        ) : (
                          t("live_send")
                        )}
                      </button>
                    </div>
                  ))}
                  {isLoading && (
                    <div className="col-span-3 flex justify-center py-3">
                      <Loader2 size={18} className="animate-spin" style={{ color: "var(--accent)" }} />
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* Footer — wallet balance */}
            <div
              className="flex-shrink-0 flex items-center justify-between px-5 py-3"
              style={{ borderTop: "1px solid var(--border-soft)" }}
            >
              <div className="flex items-center gap-1.5">
                <span className="text-lg">🪙</span>
                <span className="text-sm font-bold" style={{ color: "var(--text-primary)" }}>
                  {walletBalance.toLocaleString()}
                </span>
                <span className="text-xs" style={{ color: "var(--text-muted)" }}>
                  {t("live_coins")}
                </span>
              </div>
              <button
                onClick={() => { router.push("/wallet"); onClose(); }}
                className="flex items-center gap-1 px-3 py-1.5 rounded-full text-xs font-bold transition-all active:scale-95"
                style={{
                  background: "rgba(var(--accent-rgb),0.12)",
                  color: "var(--accent)",
                  border: "1px solid rgba(var(--accent-rgb),0.25)",
                }}
              >
                <Plus size={12} />
                {t("live_addCoins")}
              </button>
            </div>
          </motion.div>
        </>
      )}
    </AnimatePresence>
  );
}
