"use client";

import React, { useState, useRef, useEffect } from "react";
import Image from "next/image";
import BoldIcon from "@/components/ui/BoldIcon";

interface MediaFile {
  src: string;
  type?: "image" | "video"; // اختیاری
}

interface SwipeImageSliderProps {
  mediaFiles: MediaFile[];
  setImageLoading?: React.Dispatch<React.SetStateAction<boolean>>;
}

const SwipeImageSlider: React.FC<SwipeImageSliderProps> = ({
  mediaFiles,
  setImageLoading,
}) => {
  const [currentIndex, setCurrentIndex] = useState(0);
  const [isDragging, setIsDragging] = useState(false);
  const startX = useRef<number | null>(null);
  const sliderRef = useRef<HTMLDivElement>(null);

  // ریست انیمیشن در صورت تغییر تعداد تصاویر
  useEffect(() => {
    setCurrentIndex(0);
  }, [mediaFiles.length]);

  const goToPrev = () => {
    setCurrentIndex((prev) => (prev > 0 ? prev - 1 : mediaFiles.length - 1));
  };

  const goToNext = () => {
    setCurrentIndex((prev) => (prev < mediaFiles.length - 1 ? prev + 1 : 0));
  };

  const handleStart = (clientX: number) => {
    startX.current = clientX;
    setIsDragging(true);
  };

  const handleEnd = (clientX: number) => {
    if (!startX.current || !isDragging) return;

    const diff = clientX - startX.current;
    if (Math.abs(diff) > 50) {
      if (diff > 0) {
        goToPrev();
      } else {
        goToNext();
      }
    }
    

    startX.current = null;
    setIsDragging(false);
  };

  const handleMouseDown = (e: React.MouseEvent) => handleStart(e.clientX);
  const handleMouseUp = (e: React.MouseEvent) => handleEnd(e.clientX);
  const handleTouchStart = (e: React.TouchEvent) => handleStart(e.touches[0].clientX);
  const handleTouchEnd = (e: React.TouchEvent) => handleEnd(e.changedTouches[0].clientX);

  if (!mediaFiles || mediaFiles.length === 0) {
    return (
      <div className="w-full h-64 bg-neutral-200 dark:bg-neutral-800 rounded-2xl flex items-center justify-center">
        <p className="text-neutral-500">تصویری یافت نشد</p>
      </div>
    );
  }

  return (
    <div className="relative w-full group select-none">
      {/* اسلایدر اصلی */}
      <div
        ref={sliderRef}
        className="overflow-hidden rounded-2xl bg-neutral-100 dark:bg-neutral-900 flex flex-row-reverse"
        onMouseDown={handleMouseDown}
        onMouseUp={handleMouseUp}
        onMouseLeave={() => setIsDragging(false)}
        onTouchStart={handleTouchStart}
        onTouchEnd={handleTouchEnd}
        style={{ cursor: isDragging ? "grabbing" : "grab" }}
      >
        <div
          className="flex transition-transform duration-500 ease-out flex-row-reverse"
          style={{
            transform: `translateX(-${currentIndex * 100}%)`,
            width: `${mediaFiles.length * 100}%`,
          }}
        >
          {mediaFiles.map((file, idx) => (
            <div
              key={idx}
              className="w-full flex-shrink-0 flex justify-center items-center p-2"
              style={{ width: "100%" }}
            >
              {file.type === "video" ? (
                <video
                  src={file.src}
                  controls
                  className="max-h-[60vh] w-auto rounded-xl shadow-lg"
                  onLoadedData={() => setImageLoading?.(false)}
                />
              ) : (
                <Image
                  src={file.src}
                  alt={`media-${idx}`}
                  width={1000}
                  height={1000}
                  priority={idx === 0}
                  loading={idx === 0 ? "eager" : "lazy"}
                  className="object-contain w-full min-h-[30vh] rounded-xl shadow-lg transition-opacity duration-300"
                  onLoadingComplete={() => setImageLoading?.(false)}
                  unoptimized
                />
              )}
            </div>
          ))}
        </div>
      </div>

      {/* دکمه‌های ناوبری (هاور) */}
      {mediaFiles.length > 1 && (
        <>
          <button
            onClick={goToPrev}
            className="absolute left-4 top-1/2 -translate-y-1/2 w-10 h-10 bg-black/40 hover:bg-black/60 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-300 backdrop-blur-sm"
            aria-label="تصویر قبلی"
          >
            <BoldIcon name="arrow-left-2" size={20} tinted className="text-white" />
          </button>
          <button
            onClick={goToNext}
            className="absolute right-4 top-1/2 -translate-y-1/2 w-10 h-10 bg-black/40 hover:bg-black/60 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-300 backdrop-blur-sm"
            aria-label="تصویر بعدی"
          >
            <BoldIcon name="arrow-right-2" size={20} tinted className="text-white" />
          </button>
        </>
      )}

     

      {/* دات‌های پایین (اختیاری) */}
      {mediaFiles.length > 1 && (
        <div className="absolute bottom-3 left-1/2 flex-row-reverse -translate-x-1/2 flex gap-1">
          {mediaFiles.map((_, idx) => (
            <button
              key={idx}
              onClick={() => setCurrentIndex(idx)}
              className={`w-1.5 h-1.5 rounded-full transition-all duration-300 ${
                idx === currentIndex
                  ? "bg-white w-6"
                  : "bg-white/50 hover:bg-white/80"
              }`}
              aria-label={`برو به اسلاید ${idx + 1}`}
            />
          ))}
        </div>
      )}
    </div>
  );
};

export default SwipeImageSlider;