"use client";

import { useCallback, useEffect, useState } from "react";
import { Clock, AlertCircle } from "lucide-react";
import { useAppDispatch, useAppSelector } from "@/store/hooks";
import { fetchHistory, removeHistoryItem } from "@/store/slices/historySlice";
import type { ContentItem } from "@/types/content";
import { HISTORY_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 HistoryPage() {
  const dispatch = useAppDispatch();
  const { t } = useTranslation();
  const [activeTabId, setActiveTabId] = useState(1);

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

  const activeTab = CONTENT_TYPE_MAP[activeTabId];

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

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

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

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

  const handleDeleteItem = (item: ContentItem) => {
    dispatch(removeHistoryItem({ contentType: item.contentType, contentId: item.id }));
  };

  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 left-4 w-28 h-28 rounded-full pointer-events-none" style={{ background: "radial-gradient(circle,rgba(var(--accent-rgb),0.13) 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)" }}>
            <Clock 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("history_title")}</h1>
            {!isLoading && totalRows > 0 && (
              <p className="text-[11px] mt-0.5" style={{ color: "#666" }}>{totalRows} {totalRows !== 1 ? t("history_itemsWatched") : t("history_itemWatched")}</p>
            )}
          </div>
        </div>
      </div>

      {/* Tabs */}
      <ContentTabBar tabIds={HISTORY_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(fetchHistory({ 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)" }}>
              <Clock 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 {activeTab?.label.toLowerCase()} {t("history_title").toLowerCase()}</p>
              <p className="text-xs mt-1" style={{ color: "#555" }}>{t("history_watchMore")}</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} onDeleteItem={handleDeleteItem} />

            <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">
                  <Clock size={11} style={{ color: "#444" }} strokeWidth={1.5} />
                  <span className="text-[11px] font-medium" style={{ color: "#444" }}>{t("history_endOf")}</span>
                </div>
                <div className="h-px flex-1" style={{ background: "var(--border-soft)" }} />
              </div>
            )}
          </>
        )}
      </div>
    </>
  );
}
