"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import { Star, Quote, ChevronLeft, ChevronRight } from "lucide-react";
import { m } from "framer-motion";
import { Container } from "@/components/common/Container";
import { SectionHeading } from "@/components/common/SectionHeading";
import { Card, CardContent } from "@/components/common/Card";
import { Reveal } from "@/components/motion/Reveal";
import { TESTIMONIALS } from "@/data/testimonials";
import { useTranslation } from "@/hooks/useTranslation";
import { cn } from "@/lib/utils";
import type { Testimonial } from "@/types";

const AUTO_MS = 6000;
const TOTAL = TESTIMONIALS.length;
const EASE: [number, number, number, number] = [0.16, 1, 0.3, 1];

export function Testimonials() {
  const { t, dir } = useTranslation();
  const [perPage, setPerPage] = useState(3);
  const [index, setIndex] = useState(0);
  const [paused, setPaused] = useState(false);

  useEffect(() => {
    function update() {
      const w = window.innerWidth;
      if (w < 640) setPerPage(1);
      else if (w < 1024) setPerPage(2);
      else setPerPage(3);
    }
    update();
    window.addEventListener("resize", update);
    return () => window.removeEventListener("resize", update);
  }, []);

  const maxIndex = Math.max(0, TOTAL - perPage);
  const safeIndex = Math.min(index, maxIndex);

  useEffect(() => {
    if (paused || maxIndex === 0) return;
    const id = window.setInterval(() => {
      setIndex((i) => (i >= maxIndex ? 0 : i + 1));
    }, AUTO_MS);
    return () => window.clearInterval(id);
  }, [paused, maxIndex]);

  function go(delta: number) {
    setIndex((i) => {
      const next = i + delta;
      if (next < 0) return maxIndex;
      if (next > maxIndex) return 0;
      return next;
    });
  }

  const trackWidthPercent = (TOTAL / perPage) * 100;
  const slotWidthPercent = 100 / TOTAL;
  const offsetPercent = -safeIndex * slotWidthPercent;
  const dotCount = maxIndex + 1;

  return (
    <section className="section relative bg-slate-50/50 dark:bg-white/[0.02]">
      <Container>
        <SectionHeading
          eyebrow={t("testimonials.eyebrow")}
          title={t("testimonials.title")}
          subtitle={t("testimonials.subtitle")}
        />

        <Reveal delay={0.1} className="mt-14">
          <div
            className="relative"
            onMouseEnter={() => setPaused(true)}
            onMouseLeave={() => setPaused(false)}
            onFocus={() => setPaused(true)}
            onBlur={() => setPaused(false)}
            aria-roledescription="carousel"
            aria-label={t("testimonials.title")}
          >
            <div className="-mx-2 overflow-hidden">
              <m.div
                className="flex"
                style={{ width: `${trackWidthPercent}%` }}
                animate={{ x: `${offsetPercent}%` }}
                transition={{ duration: 0.55, ease: EASE }}
                drag="x"
                dragConstraints={{ left: 0, right: 0 }}
                dragElastic={0.18}
                onDragEnd={(_, info) => {
                  const threshold = 60;
                  if (info.offset.x < -threshold) go(dir === "rtl" ? -1 : 1);
                  else if (info.offset.x > threshold) go(dir === "rtl" ? 1 : -1);
                }}
              >
                {TESTIMONIALS.map((tm) => (
                  <div
                    key={tm.id}
                    className="px-2"
                    style={{ width: `${slotWidthPercent}%` }}
                  >
                    <TestimonialCard tm={tm} />
                  </div>
                ))}
              </m.div>
            </div>

            <div className="mt-8 flex items-center justify-between gap-4">
              <div className="flex items-center gap-2">
                <button
                  type="button"
                  onClick={() => go(-1)}
                  aria-label={t("testimonials.prevAria")}
                  className="grid h-10 w-10 place-items-center rounded-full border border-slate-200 bg-white text-slate-600 transition hover:-translate-y-0.5 hover:border-slate-300 hover:shadow-soft dark:border-white/[0.08] dark:bg-white/[0.04] dark:text-slate-300 dark:hover:border-white/[0.16]"
                >
                  <ChevronLeft
                    className="h-4 w-4"
                    style={{ transform: dir === "rtl" ? "scaleX(-1)" : undefined }}
                  />
                </button>
                <button
                  type="button"
                  onClick={() => go(1)}
                  aria-label={t("testimonials.nextAria")}
                  className="grid h-10 w-10 place-items-center rounded-full border border-slate-200 bg-white text-slate-600 transition hover:-translate-y-0.5 hover:border-slate-300 hover:shadow-soft dark:border-white/[0.08] dark:bg-white/[0.04] dark:text-slate-300 dark:hover:border-white/[0.16]"
                >
                  <ChevronRight
                    className="h-4 w-4"
                    style={{ transform: dir === "rtl" ? "scaleX(-1)" : undefined }}
                  />
                </button>
              </div>

              <div
                className="flex items-center gap-1.5"
                role="tablist"
                aria-label={t("testimonials.chooseAria")}
              >
                {Array.from({ length: dotCount }).map((_, i) => {
                  const active = i === safeIndex;
                  return (
                    <button
                      key={i}
                      type="button"
                      role="tab"
                      aria-selected={active}
                      aria-label={t("testimonials.goToAria").replace("{n}", String(i + 1))}
                      onClick={() => setIndex(i)}
                      className={cn(
                        "h-1.5 rounded-full transition-all duration-300",
                        active
                          ? "w-6 bg-brand-600 dark:bg-brand-400"
                          : "w-1.5 bg-slate-300 hover:bg-slate-400 dark:bg-white/[0.12] dark:hover:bg-white/[0.2]",
                      )}
                    />
                  );
                })}
              </div>
            </div>
          </div>
        </Reveal>
      </Container>
    </section>
  );
}

function TestimonialCard({ tm }: { tm: Testimonial }) {
  return (
    <Card className="h-full">
      <CardContent className="flex h-full flex-col gap-5">
        <Quote className="h-8 w-8 text-brand-500/40" aria-hidden />
        <div className="flex items-center gap-0.5" aria-label={`${tm.rating} out of 5`}>
          {Array.from({ length: 5 }).map((_, i) => (
            <Star
              key={i}
              className={
                i < tm.rating
                  ? "h-4 w-4 fill-amber-400 text-amber-400"
                  : "h-4 w-4 text-slate-300 dark:text-white/[0.12]"
              }
            />
          ))}
        </div>
        <p className="flex-1 text-base leading-[1.7] text-slate-700 dark:text-slate-200">
          &ldquo;{tm.message}&rdquo;
        </p>
        <div className="flex items-center gap-3 border-t border-slate-200/70 pt-5 dark:border-white/[0.06]">
          <Image
            src={tm.avatar}
            alt=""
            width={44}
            height={44}
            className="h-11 w-11 shrink-0 rounded-full object-cover shadow-soft"
          />
          <div className="min-w-0">
            <p className="truncate text-sm font-semibold text-slate-900 dark:text-white">
              {tm.name}
            </p>
            <p className="truncate text-xs text-slate-500 dark:text-slate-400">
              <span className="me-1" aria-hidden>
                {tm.flag}
              </span>
              {tm.role} · {tm.country}
            </p>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
