"use client";

import { useCallback, useEffect, useState } from "react";
import { Heart, AlertCircle } from "lucide-react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchLikedContent } from "@/store/slices/likedContentSlice";
import { LIKED_TABS, CONTENT_TYPE_MAP } from "@/config/contentTypes";
import {
  ContentTabBar,
  ContentRenderer,
  SkeletonRenderer,
} from "@/components/shared/ContentRenderer";
import { useInfiniteScroll } from "@/hooks/useInfiniteScroll";
import { useTranslation } from "@/i18n";

export default function LikedPage() {
  const dispatch = useAppDispatch();
  const { t } = useTranslation();
  const [activeTabId, setActiveTabId] = useState(1);

  const {
    items,
    isLoading,
    isLoadingMore,
    error,
    hasMore,
    currentPage,
    activeContentType,
    totalRows,
  } = useAppSelector((s) => s.likedContent);

  const activeTab = CONTENT_TYPE_MAP[activeTabId];

  useEffect(() => {
    dispatch(fetchLikedContent({ contentType: 1, pageNo: 1 }));
  }, [dispatch]);

  const handleLoadMore = useCallback(() => {
    dispatch(fetchLikedContent({ contentType: activeContentType, pageNo: currentPage + 1 }));
  }, [dispatch, activeContentType, currentPage]);

  const sentinelRef = useInfiniteScroll({
    hasMore,
    isLoading: isLoading || isLoadingMore,
    onLoadMore: handleLoadMore,
  });

  const handleTabChange = (id: number) => {
    setActiveTabId(id);
    dispatch(fetchLikedContent({ contentType: id, pageNo: 1 }));
  };

  return (
    <>
      {/* Header */}
      <div
        className="relative px-5 pt-7 pb-6 overflow-hidden"
        style={{
          background:
            "linear-gradient(180deg,rgba(var(--accent-rgb),0.07) 0%,transparent 100%)",
          borderBottom: "1px solid var(--border-soft)",
        }}
      >
        <div
          className="absolute top-4 left-5 w-24 h-24 rounded-full pointer-events-none"
          style={{
            background:
              "radial-gradient(circle,rgba(var(--accent-rgb),0.18) 0%,transparent 70%)",
            animation: "heart-glow-pulse 3s ease-in-out infinite",
          }}
        />
        <div className="flex items-center gap-4">
          <div
            className="w-12 h-12 rounded-2xl flex items-center justify-center shrink-0"
            style={{
              background: "rgba(var(--accent-rgb),0.12)",
              border: "1px solid rgba(var(--accent-rgb),0.22)",
              animation: "heart-beat-once 0.7s ease 0.3s both",
            }}
          >
            <Heart size={22} fill="var(--accent)" strokeWidth={0} />
          </div>
          <div>
            <h1 className="text-lg font-black tracking-tight leading-tight" style={{ color: "var(--text-primary)" }}>
              {t("liked_title")}
            </h1>
            {!isLoading && totalRows > 0 && (
              <p className="text-[11px] mt-0.5" style={{ color: "#777" }}>
                {totalRows} {totalRows !== 1 ? t("liked_itemsIn") : t("liked_itemIn")}
              </p>
            )}
          </div>
        </div>
      </div>

      {/* Tabs */}
      <ContentTabBar
        tabIds={LIKED_TABS}
        activeId={activeTabId}
        onChange={handleTabChange}
      />

      {/* Content */}
      <div className="px-5 py-5 pb-28">
        {isLoading ? (
          <SkeletonRenderer contentTypeId={activeTabId} />
        ) : error ? (
          <div className="flex flex-col items-center justify-center py-24 gap-4">
            <AlertCircle size={36} color="#555" strokeWidth={1.2} />
            <p className="text-sm" style={{ color: "#888" }}>
              {error}
            </p>
            <button
              onClick={() =>
                dispatch(
                  fetchLikedContent({ contentType: activeTabId, pageNo: 1 }),
                )
              }
              className="px-5 py-2 rounded-full text-xs font-bold text-[#ffffff] active:scale-95"
              style={{ background: "var(--accent)" }}
            >
              {t("state_tryAgain")}
            </button>
          </div>
        ) : items.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-24 gap-5">
            <div
              className="w-20 h-20 rounded-full flex items-center justify-center"
              style={{
                background: "rgba(var(--accent-rgb),0.08)",
                border: "1px solid rgba(var(--accent-rgb),0.15)",
              }}
            >
              <Heart
                size={36}
                style={{ color: "var(--accent)", opacity: 0.5 }}
                strokeWidth={1.2}
              />
            </div>
            <div className="text-center">
              <p className="text-sm font-semibold" style={{ color: "var(--text-primary)" }}>
                No liked {activeTab?.label.toLowerCase()} yet
              </p>
              <p className="text-xs mt-1" style={{ color: "#666" }}>
                {t("liked_likeMore")}
              </p>
            </div>
          </div>
        ) : (
          <>
            <div className="flex items-center gap-2 mb-4">
              <span style={{ fontSize: 14 }}>{activeTab?.emoji}</span>
              <h2 className="text-sm font-bold tracking-tight" style={{ color: "var(--text-primary)" }}>
                {activeTab?.label}
              </h2>
              {totalRows > 0 && (
                <span
                  className="text-[9px] font-bold px-2 py-0.5 rounded-full"
                  style={{
                    background: "rgba(var(--accent-rgb),0.12)",
                    color: "var(--accent)",
                    border: "1px solid rgba(var(--accent-rgb),0.2)",
                  }}
                >
                  {totalRows}
                </span>
              )}
            </div>

            <ContentRenderer items={items} contentTypeId={activeTabId} />

            <div ref={sentinelRef} className="h-1 mt-4" />

            {isLoadingMore && (
              <div className="mt-4">
                <SkeletonRenderer contentTypeId={activeTabId} count={4} />
              </div>
            )}

            {!hasMore && items.length > 0 && !isLoading && !isLoadingMore && (
              <div className="flex items-center justify-center gap-2 py-8 mt-2">
                <div
                  className="h-px flex-1"
                  style={{ background: "var(--btn-ghost)" }}
                />
                <div className="flex items-center gap-1.5">
                  <Heart size={12} fill="var(--accent)" strokeWidth={0} />
                  <span
                    className="text-[11px] font-medium"
                    style={{ color: "#555" }}
                  >
                    {t("liked_allCaughtUp")}
                  </span>
                </div>
                <div
                  className="h-px flex-1"
                  style={{ background: "var(--btn-ghost)" }}
                />
              </div>
            )}
          </>
        )}
      </div>
    </>
  );
}
