import * as React from 'react';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Grid';
import Typography from '@mui/material/Typography';
import NavigateNextRoundedIcon from '@mui/icons-material/NavigateNextRounded';
import CircularProgress from '@mui/material/CircularProgress';
import { LatestProps } from "../types/props";
import { StyledTypography, TitleTypography } from "../types/styles";
import { ArticleMeta } from "./ArticleMeta";
import Fade from '@mui/material/Fade';

export default function Latest({
  articles,
  onSelectArticle,
  onLoadMore
}: LatestProps) {
  const [visibleCount, setVisibleCount] = React.useState(2);
  const [loadingMore, setLoadingMore] = React.useState(false);
  const [animating, setAnimating] = React.useState(false);
  const loaderRef = React.useRef<HTMLDivElement | null>(null);

  const displayedArticles = articles.slice(0, visibleCount);

  React.useEffect(() => {
    if (!loaderRef.current) return;

    const observer = new IntersectionObserver(
      async (entries) => {
        const first = entries[0];
        if (first.isIntersecting && !loadingMore && visibleCount < articles.length) {
          console.log('🟡 Intersection triggered — loading more blogs...');
          setLoadingMore(true);

          // simulate API load delay
          await new Promise((resolve) => setTimeout(resolve, 1000));

          if (onLoadMore) {
            console.log(`📡 Calling onLoadMore(offset=${visibleCount}, limit=2)`);
            await onLoadMore(visibleCount, 2);
          }

          setAnimating(true);
          setVisibleCount((prev) => {
            const newCount = prev + 2;
            console.log(`✅ Increasing visibleCount from ${prev} → ${newCount}`);
            return newCount;
          });

          setTimeout(() => setAnimating(false), 600);
          setLoadingMore(false);
        }
      },
      { threshold: 0.5 }
    );

    const current = loaderRef.current;
    observer.observe(current);

    console.log('👀 IntersectionObserver attached to loaderRef:', loaderRef.current);

    return () => {
      if (current) observer.unobserve(current);
      console.log('🧹 IntersectionObserver detached');
    };
  }, [loadingMore, visibleCount, articles.length, onLoadMore]);

  return (
    <Box>
      <Typography variant="h2" gutterBottom>
        Latest
      </Typography>
      <Grid container spacing={8} columns={12} sx={{ my: 4 }}>
        {displayedArticles.map((article, index) => (
          <Grid key={index} size={{ xs: 12, sm: 6 }}>
            <Fade in timeout={animating ? 700 : 0}>
              <Box
                sx={{
                  display: 'flex',
                  flexDirection: 'column',
                  justifyContent: 'space-between',
                  gap: 1,
                  height: '100%',
                  transition: 'transform 0.3s ease',
                  '&:hover': { transform: 'translateY(-3px)' },
                }}
              >
                <Typography gutterBottom variant="caption" component="div">
                  {article.tag}
                </Typography>

                <TitleTypography
                  gutterBottom
                  variant="h6"
                  tabIndex={0}
                  onClick={() => onSelectArticle?.(index)}
                >
                  {article.title}
                  <NavigateNextRoundedIcon className="arrow" sx={{ fontSize: '1rem' }} />
                </TitleTypography>

                <StyledTypography variant="body2" color="text.secondary" gutterBottom>
                  {article.description}
                </StyledTypography>

                <ArticleMeta article={article} />
              </Box>
            </Fade>
          </Grid>
        ))}
      </Grid>

      <Box
        ref={loaderRef}
        sx={{
          display: 'flex',
          justifyContent: 'center',
          py: 3,
          opacity: loadingMore ? 1 : 0.6,
          transition: 'opacity 0.4s ease',
        }}
      >
        {loadingMore ? (
          <CircularProgress size={32} thickness={5} />
        ) : (
          <Typography variant="caption">Scroll to load more...</Typography>
        )}
      </Box>
    </Box>
  );
}
