"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import { IconPlayerPauseFilled, IconPlayerPlayFilled, IconPoint, IconPointFilled } from '@tabler/icons-react';

function getInitials(name: string) {
  return name
    .split(/\s+/)
    .map((part) => part[0]?.toUpperCase() ?? "")
    .slice(0, 2)
    .join("");
}

type Testimonial = {
  name: string;
  title: string;
  avatar?: string;
  quote: string;
};

type TestimonialsProps = {
  items: Testimonial[];
};

export default function Testimonials({ items }: TestimonialsProps) {
  const [activeIndex, setActiveIndex] = useState(0);
  const [isPlaying, setIsPlaying] = useState(true);
  const active = items[activeIndex];

  if (!active) return null;

  useEffect(() => {
    if (items.length <= 1 || !isPlaying) return;

    const id = setInterval(() => {
      setActiveIndex((i) => (i + 1) % items.length);
    }, 5000);

    return () => clearInterval(id);
  }, [items.length, isPlaying]);

  // TODO: fix bug - when clicking a pagination button, the auto-rotation timer doesn't reset, causing it to immediately rotate to the next testimonial after 5 seconds instead of 10

  return (
    <section className="w-full">
      {/* header: avatar + name + title */}
      <header className="flex items-center gap-3 mb-2">
        {active.avatar ? (
          <Image
            src={active.avatar}
            alt={active.name}
            width={64}
            height={64}
            className="rounded-full object-cover size-10"
          />
        ) : (
          <div
            aria-hidden
            className="size-10 rounded-full bg-neutral-800 flex items-center justify-center text-xs font-medium text-neutral-400"
          >
            {getInitials(active.name)}
          </div>
        )}
        <div>
          <div className="text-sm font-semibold">{active.name}</div>
          <div className="text-xs text-neutral-500">{active.title}</div>
        </div>
      </header>

      <blockquote className="p-3">"{active.quote}"</blockquote>

      <footer className="flex items-center justify-between">
        <div className="flex mt-3">
          {items.map((_, i) => (
            <button
              key={i}
              onClick={() => setActiveIndex(i)}
              aria-label={`Go to testimonial ${i + 1}`}
            >
              {i === activeIndex ? <IconPointFilled /> : <IconPoint />}
            </button>
          ))}
        </div>

        {/* TODO: play/pause button + auto-rotate timer */}
        <button onClick={() => setIsPlaying(!isPlaying)} aria-label={isPlaying ? "Pause" : "Play"}>
          {isPlaying ? <IconPlayerPauseFilled size={20} /> : <IconPlayerPlayFilled size={20} />}
        </button>
      </footer>
    </section>
  );
}
