"use client";

import { useCallback, useEffect, useState } from "react";
import { BookMarked, AlertCircle } from "lucide-react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchWatchLaterList } from "@/store/slices/watchLaterSlice";
import { WATCH_LATER_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 WatchLater() {
  const dispatch = useAppDispatch();
  const { t } = useTranslation();
  const [activeTabId, setActiveTabId] = useState(1);

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

  const activeTab = CONTENT_TYPE_MAP[activeTabId];

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

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

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

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

  return (
    <>
      {/* Header */}
      <div
        className="relative px-5 pt-6 pb-5 overflow-hidden"
        style={{ background: "linear-gradient(180deg,rgba(var(--accent-rgb),0.06) 0%,transparent 100%)", borderBottom: "1px solid var(--border-soft)" }}
      >
        <div className="absolute top-3 right-8 w-32 h-32 rounded-full pointer-events-none" style={{ background: "radial-gradient(circle,rgba(var(--accent-rgb),0.1) 0%,transparent 70%)" }} />
        <div className="flex items-center gap-3.5">
          <div className="w-11 h-11 rounded-xl flex items-center justify-center shrink-0" style={{ background: "rgba(var(--accent-rgb),0.11)", border: "1px solid rgba(var(--accent-rgb),0.2)" }}>
            <BookMarked size={20} style={{ color: "var(--accent)" }} strokeWidth={1.8} />
          </div>
          <div>
            <h1 className="text-base font-black tracking-tight leading-tight" style={{ color: "var(--text-primary)" }}>{t("watchLater_title")}</h1>
            {!isLoading && totalRows > 0 && (
              <p className="text-[11px] mt-0.5" style={{ color: "#666" }}>{totalRows} {totalRows !== 1 ? t("watchLater_savedItems") : t("watchLater_savedItem")}</p>
            )}
          </div>
        </div>
      </div>

      {/* Tabs */}
      <ContentTabBar tabIds={WATCH_LATER_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(fetchWatchLaterList({ 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.07)", border: "1px solid rgba(var(--accent-rgb),0.14)" }}>
              <BookMarked size={34} style={{ color: "var(--accent)", opacity: 0.4 }} strokeWidth={1.2} />
            </div>
            <div className="text-center">
              <p className="text-sm font-semibold" style={{ color: "var(--text-primary)" }}>No saved {activeTab?.label.toLowerCase()}</p>
              <p className="text-xs mt-1" style={{ color: "#555" }}>{t("watchLater_saveMore")}</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(--border-soft)" }} />
                <div className="flex items-center gap-1.5">
                  <BookMarked size={11} style={{ color: "#444" }} strokeWidth={1.5} />
                  <span className="text-[11px] font-medium" style={{ color: "#444" }}>{t("watchLater_allShown")}</span>
                </div>
                <div className="h-px flex-1" style={{ background: "var(--border-soft)" }} />
              </div>
            )}
          </>
        )}
      </div>
    </>
  );
}
