import React, { useEffect, useState } from "react";
import { Box, Grid, Typography } from "@mui/material";
import { motion, useAnimation } from "framer-motion";
import { useInView } from "react-intersection-observer";
import darkbackground from "../../../dark-background.jpg"

// Counter Component
const Counter = ({ target, label, icon }: { target: number; label: string; icon: React.ReactNode }) => {
  const controls = useAnimation();
  const [count, setCount] = useState(0);
  const { ref, inView } = useInView({ triggerOnce: true });

  useEffect(() => {
    if (inView) {
      let start = 0;
      const step = Math.ceil(target / 50);
      const interval = setInterval(() => {
        start += step;
        setCount(start > target ? target : start);
        if (start >= target) clearInterval(interval);
      }, 20);
    }
  }, [inView, target]);

  return (
    <motion.div ref={ref} animate={controls} initial={{ opacity: 0, y: 20 }} whileInView={{ opacity: 1, y: 0 }} transition={{ duration: 0.6 }}>
      <Box textAlign="center">
        {icon}
        <Typography variant="h6" color="white" sx={{ mt: 1 }}>
          {label}
        </Typography>
        <Typography variant="h4" fontWeight="bold" color="white">
          {count}
        </Typography>
      </Box>
    </motion.div>
  );
};


const StatsSection = () => {
  return (
    <Box
      sx={{
        position: "relative",
        backgroundImage: `url(${darkbackground})`,
        backgroundSize: "cover",
        backgroundAttachment: "fixed", 
        backgroundPosition: "center",
        minHeight: "80vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        color: "white",
        py: 10,
      }}
    >
      <Grid container spacing={1} justifyContent="center">
        {/* Coffee Cups */}
        <Grid item xs={6} md={3}>
          <Counter target={20800} label="COFFEE CUPS" icon={<Typography fontSize={40}>☕</Typography>} />
        </Grid>

        {/* Projects */}
        <Grid item xs={6} md={3}>
          <Counter target={575} label="PROJECTS" icon={<Typography fontSize={40}>💼</Typography>} />
        </Grid>

        {/* Working Days */}
        <Grid item xs={6} md={3}>
          <Counter target={4412} label="WORKING DAYS" icon={<Typography fontSize={40}>🖱️</Typography>} />
        </Grid>

        {/* Clients */}
        <Grid item xs={6} md={3}>
          <Counter target={498} label="CLIENTS" icon={<Typography fontSize={40}>👥</Typography>} />
        </Grid>
      </Grid>
    </Box>
  );
};

export default StatsSection;
