"use client";

import Container from "@/components/Container/Container";
import Section from "@/components/Section/Section";
import type { HomeTestimonial } from "@/content/homeTestimonials";
import Image from "next/image";
import { useCallback, useEffect, useRef, useState } from "react";
import { CSSTransition, SwitchTransition } from "react-transition-group";
import styles from "./TestimonialCarousel.module.css";

const INTERVAL_MS = 4000;

type TestimonialCarouselProps = {
  testimonials: HomeTestimonial[];
  intervalMs?: number;
  id?: string;
};

const TestimonialSlide = ({ testimonial }: { testimonial: HomeTestimonial }) => {
  const { image, name } = testimonial;

  return (
    <>
      <div>
        {image && (
          <Image
            className="rounded-xl xl:block hidden absolute -left-[120px]"
            src={image}
            alt={name}
            width={100}
            height={100}
          />
        )}
        <p>
          <strong>&quot;</strong>
          {testimonial.content}
          <strong>&quot;</strong>
        </p>
      </div>
      <div className="flex justify-start items-center">
        {image && (
          <Image
            className="rounded-xl block mr-xs lg:mr-0 xl:hidden"
            src={image}
            alt={name}
            width={100}
            height={100}
          />
        )}
        <div className="flex flex-col items-start justify-items-start">
          <p className={`h3 m-none ${styles.attribution}`}>
            {testimonial.name}
            {testimonial.title && <span>, {testimonial.title}</span>}
          </p>
          <p className={`m-none ${styles.attribution}`}>{testimonial.company}</p>
        </div>
      </div>
    </>
  );
};

const TestimonialCarousel = ({
  testimonials,
  intervalMs = INTERVAL_MS,
  id,
}: TestimonialCarouselProps) => {
  const [index, setIndex] = useState(0);
  const [paused, setPaused] = useState(false);
  const slideRef = useRef<HTMLDivElement>(null);

  const count = testimonials.length;
  const active = testimonials[index];

  const advance = useCallback(() => {
    setIndex((current) => (current + 1) % count);
  }, [count]);

  useEffect(() => {
    if (count <= 1 || paused) return;

    const prefersReducedMotion = window.matchMedia(
      "(prefers-reduced-motion: reduce)",
    ).matches;
    if (prefersReducedMotion) return;

    const timer = window.setInterval(advance, intervalMs);
    return () => window.clearInterval(timer);
  }, [advance, count, intervalMs, paused]);

  if (!active) return null;

  return (
    <Container bgColor="quinary" id={id}>
      <Section
        gridArea="thin"
        className={`overflow-visible text-white ${styles.root}`}
        aria-label="Client testimonials"
        onMouseEnter={() => setPaused(true)}
        onMouseLeave={() => setPaused(false)}
        onFocusCapture={() => setPaused(true)}
        onBlurCapture={(e) => {
          if (!e.currentTarget.contains(e.relatedTarget)) {
            setPaused(false);
          }
        }}
      >
        <div className={styles.slideWrap} aria-live="polite" aria-atomic="true">
          <SwitchTransition mode="out-in">
            <CSSTransition
              key={index}
              nodeRef={slideRef}
              timeout={400}
              classNames={{
                enter: styles.fadeEnter,
                enterActive: styles.fadeEnterActive,
                exit: styles.fadeExit,
                exitActive: styles.fadeExitActive,
              }}
            >
              <div ref={slideRef}>
                <TestimonialSlide testimonial={active} />
              </div>
            </CSSTransition>
          </SwitchTransition>
        </div>
      </Section>
    </Container>
  );
};

export default TestimonialCarousel;
