import {
  Avatar,
  Box,
  Card,
  CardContent,
  Typography,
  IconButton,
} from "@mui/material";
import { motion, AnimatePresence, useAnimation, Variants } from "framer-motion";
import { useEffect, useState } from "react";
import { KeyboardArrowLeft, KeyboardArrowRight } from "@mui/icons-material";
import testimonialImg from "../testomonials/b7bef0298c881712fbc6437106d2aaef27c4fad8.jpg";

const testimonials = [
  {
    name: "Sarah Johnson",
    role: "Marketing Director",
    company: "Tech Innovations Inc.",
    feedback: "Working with this team transformed our digital presence.",
    rating: 5,
  },
  {
    name: "Michael Chen",
    role: "Sr. Manager",
    company: "Wells Fargo",
    feedback: "Exceptional service from start to finish.",
    rating: 5,
  },
  {
    name: "Emily Rodriguez",
    role: "Product Owner",
    company: "Nexus Enterprises",
    feedback: "The team's technical expertise was outstanding.",
    rating: 4,
  },
];

// Properly typed animation variants
const containerVariants: Variants = {
  hidden: { opacity: 0 },
  visible: {
    opacity: 1,
    transition: {
      staggerChildren: 0.2,
      duration: 0.8,
    },
  },
};

const itemVariants: Variants = {
  hidden: { y: 50, opacity: 0 },
  visible: {
    y: 0,
    opacity: 1,
    transition: {
      duration: 0.6,
      ease: "easeOut", // Using string literal instead of array
    },
  },
  hover: {
    y: -10,
    transition: { duration: 0.3 },
  },
};

const Testimonials = () => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isMobile, setIsMobile] = useState(false);
  const controls = useAnimation();

  useEffect(() => {
    const handleResize = () => {
      setIsMobile(window.innerWidth < 600);
    };
    handleResize();
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  useEffect(() => {
    if (!isMobile) return;

    const timer = setInterval(() => {
      handleNext();
    }, 5000);

    return () => clearInterval(timer);
  }, [currentIndex, isMobile]);

  const handleNext = () => {
    controls
      .start({
        x: "-100%",
        opacity: 0,
        transition: { duration: 0.3 },
      })
      .then(() => {
        setCurrentIndex((prev) => (prev + 1) % testimonials.length);
        controls
          .start({
            x: "100%",
            opacity: 0,
          })
          .then(() => {
            controls.start({
              x: 0,
              opacity: 1,
              transition: { duration: 0.5 },
            });
          });
      });
  };

  const handlePrev = () => {
    controls
      .start({
        x: "100%",
        opacity: 0,
        transition: { duration: 0.3 },
      })
      .then(() => {
        setCurrentIndex(
          (prev) => (prev - 1 + testimonials.length) % testimonials.length
        );
        controls
          .start({
            x: "-100%",
            opacity: 0,
          })
          .then(() => {
            controls.start({
              x: 0,
              opacity: 1,
              transition: { duration: 0.5 },
            });
          });
      });
  };

  return (
    <Box
      sx={{
        backgroundColor: "#1d2733",
        color: "#fff",
        py: { xs: 6, md: 10 },
        px: { xs: 2, md: 3 },
        overflow: "hidden",
      }}
    >
      {/* Header Section */}
      <Box
        component={motion.div}
        initial="hidden"
        animate="visible"
        variants={containerVariants}
        textAlign="center"
        mb={{ xs: 4, md: 6 }}
        sx={{ maxWidth: 800, mx: "auto" }}
      >
        <Typography variant="h3" fontWeight="bold" gutterBottom>
          Testimonials
        </Typography>
        <Typography variant="subtitle1">
          Don't just take our word for it
        </Typography>
      </Box>

      {/* Mobile Carousel */}
      {isMobile ? (
        <Box sx={{ position: "relative", height: 450 }}>
          <AnimatePresence>
            <Box
              component={motion.div}
              key={currentIndex}
              animate={controls}
              initial={{ x: 0, opacity: 1 }}
              exit={{ x: 0, opacity: 0 }}
              sx={{
                position: "absolute",
                width: "100%",
                display: "flex",
                justifyContent: "center",
              }}
            >
              <TestimonialCard testimonial={testimonials[currentIndex]} />
            </Box>
          </AnimatePresence>

          <NavigationArrows handlePrev={handlePrev} handleNext={handleNext} />
        </Box>
      ) : (
        /* Desktop Grid */
        <Box
          component={motion.div}
          initial="hidden"
          animate="visible"
          variants={containerVariants}
          sx={{
            display: "flex",
            justifyContent: "center",
            flexWrap: "wrap",
            gap: 4,
            px: { md: 4 },
          }}
        >
          {testimonials.map((t, idx) => (
            <Box
              key={idx}
              component={motion.div}
              variants={itemVariants}
              whileHover="hover"
              sx={{
                width: { md: 350 },
                flex: { md: "1 1 300px" },
              }}
            >
              <TestimonialCard testimonial={t} />
            </Box>
          ))}
        </Box>
      )}
    </Box>
  );
};

// Extracted Card Component
const TestimonialCard = ({
  testimonial,
}: {
  testimonial: (typeof testimonials)[0];
}) => (
  <Card
    sx={{
      borderRadius: 3,
      width: "100%",
      minHeight: 400,
      textAlign: "center",
      py: 3,
      px: 2,
      background: "linear-gradient(145deg, #1d2733, #232f3e)",
      boxShadow: "0 8px 32px rgba(0, 0, 0, 0.2)",
      border: "1px solid rgba(0, 225, 255, 0.1)",
      transition: "all 0.3s ease",
      "&:hover": {
        boxShadow: "0 12px 40px rgba(0, 225, 255, 0.15)",
        borderColor: "rgba(0, 225, 255, 0.3)",
        transform: "translateY(-5px)",
      },
    }}
  >
    <Avatar
      src={testimonialImg}
      alt={testimonial.name}
      sx={{
        width: 80,
        height: 80,
        margin: "0 auto",
        mb: 2,
        border: "2px solid #00e1ff",
        boxShadow: "0 0 15px rgba(0, 225, 255, 0.4)",
      }}
    />
    <CardContent>
      <Typography variant="h6" fontWeight="bold" color="#00e1ff">
        {testimonial.name}
      </Typography>
      <Typography variant="subtitle1" color="rgba(255,255,255,0.8)" mb={0.5}>
        {testimonial.role}
      </Typography>
      <Typography variant="body2" color="rgba(255,255,255,0.6)" mb={2}>
        {testimonial.company}
      </Typography>
      <Typography
        variant="body1"
        color="rgba(255,255,255,0.8)"
        mb={3}
        fontStyle="italic"
      >
        {testimonial.feedback}
      </Typography>
      <Box>
        {Array.from({ length: 5 }).map((_, i) => (
          <Box
            component="span"
            key={i}
            sx={{
              color:
                i < testimonial.rating ? "#00e1ff" : "rgba(255,255,255,0.2)",
              fontSize: "1.5rem",
              mx: 0.5,
              textShadow:
                i < testimonial.rating
                  ? "0 0 8px rgba(0, 225, 255, 0.5)"
                  : "none",
            }}
          >
            ★
          </Box>
        ))}
      </Box>
    </CardContent>
  </Card>
);

// Extracted Navigation Component
const NavigationArrows = ({
  handlePrev,
  handleNext,
}: {
  handlePrev: () => void;
  handleNext: () => void;
}) => (
  <>
    <IconButton
      onClick={handlePrev}
      sx={{
        position: "absolute",
        left: 10,
        top: "50%",
        transform: "translateY(-50%)",
        color: "#00e1ff",
        backgroundColor: "rgba(0, 225, 255, 0.1)",
        "&:hover": {
          backgroundColor: "rgba(0, 225, 255, 0.2)",
        },
      }}
    >
      <KeyboardArrowLeft fontSize="large" />
    </IconButton>

    <IconButton
      onClick={handleNext}
      sx={{
        position: "absolute",
        right: 10,
        top: "50%",
        transform: "translateY(-50%)",
        color: "#00e1ff",
        backgroundColor: "rgba(0, 225, 255, 0.1)",
        "&:hover": {
          backgroundColor: "rgba(0, 225, 255, 0.2)",
        },
      }}
    >
      <KeyboardArrowRight fontSize="large" />
    </IconButton>
  </>
);

export default Testimonials;
