import React, { useEffect, useMemo, useRef, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { useTranslation } from "react-i18next";
import PostCard from "./PostCardNew";
import { FeedSkeleton } from "../ui/Skeleton";
import { matchesContentFilter } from "../Filters/ContentFilters";

const listVariants = {
  hidden: { opacity: 0 },
  visible: {
    opacity: 1,
    transition: { staggerChildren: 0.08 },
  },
};

const itemVariants = {
  hidden: { opacity: 0, y: 20 },
  visible: { opacity: 1, y: 0, transition: { duration: 0.4, ease: [0.16, 1, 0.3, 1] } },
};

export default function PostList({ posts, loading, error, selectedPost, onSelectPost, onPostDeleted, onPostUpdated, contentFilter = "all" }) {
  const { t } = useTranslation();
  const [visibleCount, setVisibleCount] = useState(1);
  const listRef = useRef(null);
  const sentinelRef = useRef(null);

  const filtered = useMemo(
    () => posts.filter((p) => matchesContentFilter(p, contentFilter)),
    [posts, contentFilter]
  );

  useEffect(() => {
    setVisibleCount(1);
  }, [contentFilter]);

  useEffect(() => {
    const sentinel = sentinelRef.current;
    if (!sentinel) return;
    const observer = new IntersectionObserver(
      (entries) => {
        const hit = entries && entries[0];
        if (!hit || !hit.isIntersecting) return;
        setVisibleCount((c) => Math.min(filtered.length, c + 2));
      },
      { root: null, rootMargin: "400px 0px", threshold: 0 }
    );
    observer.observe(sentinel);
    return () => observer.disconnect();
  }, [filtered.length]);

  // Show skeleton loading state
  if (loading && posts.length === 0) {
    return (
      <div className="space-y-4 p-4" ref={listRef}>
        <FeedSkeleton count={3} />
      </div>
    );
  }

  return (
    <div className="relative" ref={listRef}>
      {/* Header */}
      <motion.div
        className="sticky top-14 sm:top-16 z-50 px-4 py-3
                   bg-gradient-to-b from-surface-950/95 via-surface-900/90 to-transparent
                   backdrop-blur-sm"
        initial={{ opacity: 0, y: -10 }}
        animate={{ opacity: 1, y: 0 }}
      >
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-3">
            <div className="w-1 h-6 rounded-full bg-gradient-to-b from-accent to-purple-500" />
            <h2 className="text-lg font-bold text-surface-100">
              {t('feed.title', 'News Feed')}
            </h2>
            <span className="text-xs font-medium text-surface-500 bg-surface-800/50 px-2 py-0.5 rounded-full">
              {filtered.length}
            </span>
          </div>
          {loading && (
            <motion.div
              className="flex items-center gap-2 text-xs text-accent"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
            >
              <i className="fa-solid fa-circle-notch fa-spin" />
              <span>{t('common.loading')}</span>
            </motion.div>
          )}
        </div>
      </motion.div>

      {/* Error */}
      <AnimatePresence>
        {error && (
          <motion.div
            className="mx-4 mb-4 p-4 rounded-2xl bg-red-500/10 border border-red-500/20 text-red-400 text-sm"
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -10 }}
          >
            <i className="fa-solid fa-exclamation-triangle mr-2" />
            {error}
          </motion.div>
        )}
      </AnimatePresence>

      {/* Posts */}
      <motion.div
        className="space-y-4 px-4 pb-4"
        variants={listVariants}
        initial="hidden"
        animate="visible"
      >
        <AnimatePresence mode="popLayout">
          {filtered.slice(0, visibleCount).map((p) => (
            <motion.div
              key={p.id ?? p._id}
              variants={itemVariants}
              layout
            >
              <PostCard
                post={p}
                selected={selectedPost && (selectedPost.id ?? selectedPost._id) === (p.id ?? p._id)}
                onSelect={onSelectPost}
                onPostDeleted={onPostDeleted}
                onPostUpdated={onPostUpdated}
              />
            </motion.div>
          ))}
        </AnimatePresence>
      </motion.div>

      {/* Empty state */}
      <AnimatePresence>
        {!loading && filtered.length === 0 && (
          <motion.div
            className="flex flex-col items-center justify-center py-16 text-surface-500"
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.95 }}
          >
            <i className="fa-regular fa-newspaper text-5xl mb-4 opacity-40" />
            <p className="text-sm font-medium">{t('feed.noPosts', 'No posts found')}</p>
          </motion.div>
        )}
      </AnimatePresence>

      {/* Load more sentinel */}
      {filtered.length > visibleCount && (
        <div ref={sentinelRef} className="h-20 flex items-center justify-center">
          <motion.div
            className="flex items-center gap-2 text-sm text-surface-500"
            animate={{ opacity: [0.5, 1, 0.5] }}
            transition={{ duration: 1.5, repeat: Infinity }}
          >
            <i className="fa-solid fa-circle-notch fa-spin" />
            <span>{t('feed.loadingMore', 'Loading more...')}</span>
          </motion.div>
        </div>
      )}
    </div>
  );
}
