import ThreeDScrollTriggerRow, {
  ThreeDScrollTriggerContainer,
} from "../lightswind/ThreeDScrollTrigger";
import React, { memo, useCallback, useMemo, useState } from "react";
import { useReviews } from "../../hooks/useReviews";
import { Skeleton } from "./Skeleton";

export default function ThreeScrollTrigger() {
  const { data, isLoading } = useReviews();
  const [paused, setPaused] = useState(false);
  const handlePause = useCallback(() => setPaused(true), []);
  const handleResume = useCallback(() => setPaused(false), []);

  const reviews = useMemo(() => {
    const list = data?.data || [];
    if (!Array.isArray(list)) return [];
    return list.map((item) => ({
      name: item.name,
      company: item.about,
      image: item.profile_image,
      review: item.content,
      rating: item.rating,
    }));
  }, [data]);

  const row1 = useMemo(() => reviews.slice(0, 3), [reviews]);
  const row2 = useMemo(() => reviews.slice(3, 6), [reviews]);
  const row3 = useMemo(() => reviews.slice(6, 9), [reviews]);

  if (!isLoading && reviews.length === 0) {
    return (
      <div className="w-full mx-auto max-w-[1400px] py-10 text-center text-gray-600">
        No reviews available.
      </div>
    );
  }

  return (
    <div className="w-full mx-auto max-w-[1400px] overflow-hidden">
      <ThreeDScrollTriggerContainer className="py-8 space-y-8">
        {/* Row 1 - 3 Cards scrolling right */}
        <ThreeDScrollTriggerRow baseVelocity={2} direction={1} paused={paused}>
          <div className="flex flex-row gap-6 px-3 py-1">
            {isLoading
              ? Array.from({ length: 3 }).map((_, idx) => (
                  <ReviewSkeleton key={`row1-skel-${idx}`} />
                ))
              : row1.map((rev, idx) => (
                  <ReviewCard
                    key={`${rev.name}-${idx}`}
                    {...rev}
                    onMouseEnter={handlePause}
                    onMouseLeave={handleResume}
                  />
                ))}
          </div>
        </ThreeDScrollTriggerRow>

        {/* Row 2 - 3 Cards scrolling left */}
        <ThreeDScrollTriggerRow baseVelocity={2} direction={-1} paused={paused}>
          <div className="flex flex-row gap-6 px-3 py-1">
            {isLoading
              ? Array.from({ length: 3 }).map((_, idx) => (
                  <ReviewSkeleton key={`row2-skel-${idx}`} />
                ))
              : row2.map((rev, idx) => (
                  <ReviewCard
                    key={`${rev.name}-${idx}`}
                    {...rev}
                    onMouseEnter={handlePause}
                    onMouseLeave={handleResume}
                  />
                ))}
          </div>
        </ThreeDScrollTriggerRow>

        {row3.length > 0 && (
          <ThreeDScrollTriggerRow baseVelocity={2} direction={1} paused={paused}>
            <div className="flex flex-row gap-6 px-3 py-1">
              {row3.map((rev, idx) => (
                <ReviewCard
                  key={`${rev.name}-${idx}`}
                  {...rev}
                  onMouseEnter={handlePause}
                  onMouseLeave={handleResume}
                />
              ))}
            </div>
          </ThreeDScrollTriggerRow>
        )}
      </ThreeDScrollTriggerContainer>
    </div>
  );
}

// Card component for clarity and reuse
const ReviewCard = memo(function ReviewCard({
  name,
  company,
  image,
  review,
  rating,
  onMouseEnter,
  onMouseLeave,
}) {
  const stars = useMemo(() => {
    if (!rating) return null;
    return Array.from({ length: 5 }, (_, i) => (
      <span key={i} className="text-[24px] ">{i < rating ? "★" : "☆"}</span>
    ));
  }, [rating]);

  return (
    <div
      className="bg-[#fbfbfb] rounded-xl shadow-md p-6 w-80 min-w-80 flex-shrink-0 hover:shadow-lg transition-shadow"
      onMouseEnter={onMouseEnter}
      onMouseLeave={onMouseLeave}
    >
      <div className="flex items-center gap-3 mb-4">
        {image ? (
          <img
            src={image}
            alt={name}
            className="w-12 h-12 rounded-full object-cover flex-shrink-0"
            loading="lazy"
          />
        ) : (
          <div className="w-12 h-12 rounded-full bg-gray-200 flex-shrink-0" />
        )}
        <div className="flex-1 min-w-0">
          <div className="font-semibold text-gray-900 truncate">{name}</div>
          <div className="text-xs text-gray-500 truncate">{company}</div>
          {stars && <div className="text-[11px] text-amber-500">{stars}</div>}
        </div>
      </div>
      <div className="text-sm text-gray-700 line-clamp-4">
        "{review}"
      </div>
    </div>
  );
});

function ReviewSkeleton() {
  return (
    <div className="bg-[#fbfbfb] rounded-xl shadow-md p-6 w-80 min-w-80 flex-shrink-0">
      <div className="flex items-center gap-3 mb-4">
        <Skeleton width={48} height={48} rounded={999} />
        <div className="flex-1 space-y-2">
          <Skeleton width="60%" height={12} />
          <Skeleton width="40%" height={10} />
        </div>
      </div>
      <Skeleton width="100%" height={10} />
      <Skeleton width="90%" height={10} className="mt-2" />
      <Skeleton width="70%" height={10} className="mt-2" />
    </div>
  );
}
