"use client";

import React, { useEffect, useCallback, useState, useRef } from "react";
import MainModelCard from "./MainModelCard";
import { Course } from "@/types/types";
import Image from "next/image";
import useAxios from "@/hooks/useAxios";
import toast from "react-hot-toast";
import { motion, AnimatePresence } from "framer-motion";

interface InfinitePostsProps {
  token: string;
  filters: {
    hashtag?: string;
    expertise?: string;
    province?: string;
    city?: string;
    userLevel?: string;
    rateFilter?: string;
    _id?: string;
    search?: string;
    category?: string;
    minPrice?: number;
    maxPrice?: number;
    hasOffer?: boolean;
    teacherName?: string;
    type?: string;
    sortBy?: string;
    sortOrder?: string;
  };
  typeFilter?: "image" | "video";
}

export default function InfinitePosts({ filters, token }: InfinitePostsProps) {
  const [courses, setCourses] = useState<Course[]>([]);
  const [coursesPage, setCoursesPage] = useState(1);
  const [hasMoreCourses, setHasMoreCourses] = useState(true);
  const [isLoadingMoreCourses, setIsLoadingMoreCourses] = useState(false);
  const [isInitialCoursesLoading, setIsInitialCoursesLoading] = useState(true);
  const [totalItems, setTotalItems] = useState(0);
  const loadMoreRef = useRef<HTMLDivElement>(null);
  const { request } = useAxios();

  // ساخت query string از فیلترها
  const buildQueryString = (page: number) => {
    const params = new URLSearchParams();
    
    // صفحه‌بندی
    params.append("page", page.toString());
    params.append("limit", "5");
    params.append("status", "accept");
    
    // فیلترهای جستجو - مطابق با بک‌اند
    if (filters?.search && filters.search.trim() !== "") {
      params.append("search", filters.search);
    }
    if (filters?.category && filters.category !== "") {
      params.append("category", filters.category);
    }
    if (filters?.minPrice && filters.minPrice > 0) {
      params.append("minPrice", filters.minPrice.toString());
    }
    if (filters?.maxPrice && filters.maxPrice > 0) {
      params.append("maxPrice", filters.maxPrice.toString());
    }
    if (filters?.hasOffer) {
      params.append("hasOffer", "true");
    }
    if (filters?.teacherName && filters.teacherName.trim() !== "") {
      params.append("teacherName", filters.teacherName);
    }
    if (filters?.type && filters.type !== "") {
      params.append("type", filters.type);
    }
    if (filters?.sortBy && filters.sortBy !== "createdAt") {
      params.append("sortBy", filters.sortBy);
    }
    if (filters?.sortOrder && filters.sortOrder !== "desc") {
      params.append("sortOrder", filters.sortOrder);
    }
    
    console.log("Query params:", params.toString());
    return params.toString();
  };

  // تابع دریافت دوره‌ها با صفحه‌بندی و فیلتر
  const fetchCourses = async (page: number, isLoadMore = false) => {
    if (isLoadMore) {
      setIsLoadingMoreCourses(true);
    }

    try {
      const queryString = buildQueryString(page);
      // آدرس صحیح API - با توجه به بک‌اند شما
      const url = `/academy/academy/get/curses${queryString ? `?${queryString}` : ""}`;
      
      console.log("Fetching URL:", url);
      
      const response = await request("GET", url);

      console.log(`Courses page ${page} response:`, response);

      let newCourses: Course[] = [];
      let total = 0;

      // بررسی ساختار پاسخ بر اساس بک‌اند
      if (response?.success && response?.data?.courses) {
        newCourses = response.data.courses;
        total = response.data.pagination?.totalItems || 0;
        setHasMoreCourses(response.data.pagination?.hasNextPage || false);
        setTotalItems(total);
      } 
      // ساختار جایگزین
      else if (response?.data?.courses) {
        newCourses = response.data.courses;
        total = response.data.pagination?.totalItems || 0;
        setHasMoreCourses(response.data.pagination?.hasNextPage || false);
        setTotalItems(total);
      }
      else if (response?.courses && Array.isArray(response.courses)) {
        newCourses = response.courses;
        setHasMoreCourses(newCourses.length === 5);
        setTotalItems(newCourses.length);
      }
      else if (Array.isArray(response)) {
        newCourses = response;
        setHasMoreCourses(newCourses.length === 5);
        setTotalItems(newCourses.length);
      }
      else {
        console.error("Unexpected response structure:", response);
        setHasMoreCourses(false);
        if (!isLoadMore) {
          setCourses([]);
        }
      }

      if (isLoadMore) {
        setCourses((prev) => [...prev, ...newCourses]);
      } else {
        setCourses(newCourses);
      }

      setCoursesPage(page);
    } catch (err: any) {
      console.error("get error:", err);
      toast.error(err?.message || "خطا در دریافت اطلاعات");
      setHasMoreCourses(false);
    } finally {
      if (isLoadMore) {
        setIsLoadingMoreCourses(false);
      }
      setIsInitialCoursesLoading(false);
    }
  };

  // بازنشانی و لود مجدد هنگام تغییر فیلترها
  useEffect(() => {
    // ریست کردن state‌ها
    setCourses([]);
    setCoursesPage(1);
    setHasMoreCourses(true);
    setIsInitialCoursesLoading(true);
    setTotalItems(0);
    
    // لود مجدد با فیلترهای جدید
    fetchCourses(1, false);
  }, [
    filters?.search,
    filters?.category,
    filters?.minPrice,
    filters?.maxPrice,
    filters?.hasOffer,
    filters?.teacherName,
    filters?.type,
    filters?.sortBy,
    filters?.sortOrder,
  ]);

  // تنظیم Intersection Observer برای لود خودکار
  useEffect(() => {
    if (!hasMoreCourses || isLoadingMoreCourses || isInitialCoursesLoading)
      return;

    const observer = new IntersectionObserver(
      (entries) => {
        if (
          entries[0].isIntersecting &&
          hasMoreCourses &&
          !isLoadingMoreCourses
        ) {
          fetchCourses(coursesPage + 1, true);
        }
      },
      { threshold: 0.1, rootMargin: "100px" }
    );

    if (loadMoreRef.current) {
      observer.observe(loadMoreRef.current);
    }

    return () => observer.disconnect();
  }, [
    hasMoreCourses,
    isLoadingMoreCourses,
    coursesPage,
    isInitialCoursesLoading,
  ]);

  if (isInitialCoursesLoading) {
    return (
      <div className="flex justify-center items-center min-h-[400px]">
        <div className="relative w-24 h-24">
          <div className="absolute inset-0 rounded-full border-4 border-gray-200 dark:border-gray-700"></div>
          <div className="absolute inset-0 rounded-full border-4 border-t-pink-500 border-r-transparent border-b-transparent border-l-transparent animate-spin"></div>
        </div>
      </div>
    );
  }

  if (courses.length === 0 && !isInitialCoursesLoading) {
    return (
      <div className="text-center py-12  rounded-2xl">
        <div className="text-6xl mb-4">📚</div>
        <p className="text-gray-600 dark:text-gray-400 text-lg">
          هیچ دوره‌ای با این فیلترها یافت نشد
        </p>
        <p className="text-gray-500 dark:text-gray-500 text-sm mt-2">
          لطفاً فیلترهای دیگری را امتحان کنید
        </p>
      </div>
    );
  }

  return (
    <div className="mt-5 space-y-4 max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 mb-24">
      {/* نمایش تعداد نتایج */}
      <div className="text-sm text-gray-500 dark:text-gray-400 mb-4">
        {totalItems.toLocaleString()} دوره پیدا شد
      </div>

      {/* نمایش دوره‌ها */}
      <AnimatePresence>
        {courses.map((post, index) => (
          <motion.div
            key={post._id || index}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: index * 0.05 }}
            className="space-y-2"
          >
            <MainModelCard postData={post} />
            <hr className="border-gray-200 dark:border-gray-700" />
          </motion.div>
        ))}
      </AnimatePresence>

      {/* المان تریگر برای لود خودکار */}
      {hasMoreCourses && courses.length > 0 && (
        <div
          ref={loadMoreRef}
          className="flex justify-center items-center py-4"
        >
          {isLoadingMoreCourses ? (
            <div className="flex justify-center items-center py-4 gap-2">
              <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-pink-500"></div>
              <span className="text-sm text-gray-500">
                در حال بارگذاری دوره‌های بیشتر...
              </span>
            </div>
          ) : (
            <div className="text-center py-4">
              <button
                onClick={() => fetchCourses(coursesPage + 1, true)}
                className="px-4 py-2 bg-pink-500 text-white rounded-lg hover:bg-pink-600 transition-colors text-sm"
              >
                بارگذاری بیشتر
              </button>
            </div>
          )}
        </div>
      )}

      {/* پیام پایان لیست */}
      {!hasMoreCourses && courses.length > 0 && (
        <div className="text-center py-4 text-gray-500 text-sm">
          به انتهای لیست دوره‌ها رسیدید ({totalItems.toLocaleString()} دوره)
        </div>
      )}
    </div>
  );
}