"use client";

import { IMAGE_BASE_URL, buildStorageUrl } from "@/components/main/BaseUrl";
import React, { useEffect, useState } from "react";
import { Academy, Course } from "@/types/types";
import Container from "@/components/elements/Container";
import useAxios from "@/hooks/useAxios";
import { useParams, useRouter } from "next/navigation";
import toast from "react-hot-toast";
import Image from "next/image";
import Link from "next/link";
import { motion } from "framer-motion";

interface Tag {
  value: string;
}

interface PaginationType {
  currentPage: number;
  totalPages: number;
  totalItems: number;
  hasNextPage: boolean;
  hasPrevPage: boolean;
}
function AcademyPage() {
  const params = useParams();
  const academyId = params?.academyId as string;
  
  const { request } = useAxios();
  const [academy, setAcademy] = useState<Academy | null>(null);
  const [courses, setCourses] = useState<Course[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isLoadingCourses, setIsLoadingCourses] = useState(false);
  const [pagination, setPagination] = useState<PaginationType>({
    currentPage: 1,
    totalPages: 1,
    totalItems: 0,
    hasNextPage: false,
    hasPrevPage: false,
  });
  const router = useRouter();

  // دریافت اطلاعات آکادمی
  useEffect(() => {
    const fetchAcademy = async () => {
      if (!academyId) {
        console.error("academyId یافت نشد");
        setIsLoading(false);
        return;
      }

      setIsLoading(true);
      
      try {
        const response = await request("POST", `/academy/findAcademyById`, {
          _id: academyId
        });
        
        let academyData = null;
        if (response?.academy) {
          academyData = response.academy;
        } else if (response?.data?.academy) {
          academyData = response.data.academy;
        } else {
          academyData = response;
        }
        
        setAcademy(academyData);
      } catch (error) {
        console.error("خطا در دریافت اطلاعات:", error);
        toast.error("خطا در دریافت اطلاعات آکادمی");
      } finally {
        setIsLoading(false);
      }
    };

    fetchAcademy();
  }, [academyId]);

  // دریافت دوره‌های آکادمی
  const fetchCourses = async (pageNum: number = 1) => {
    if (!academyId) return;
    
    setIsLoadingCourses(true);
    try {
      const response = await request(
        "GET",
        `/academy/academy/get/getAcademyCourse/${academyId}?page=${pageNum}&limit=6&status=accept`
      );
      
      console.log("دوره‌های آکادمی:", response);
      
      if (response?.success && response?.data?.courses) {
        setCourses(response.data.courses);
        if (response.data.pagination) {
          setPagination({
            currentPage: response.data.pagination.currentPage,
            totalPages: response.data.pagination.totalPages,
            totalItems: response.data.pagination.totalItems,
            hasNextPage: response.data.pagination.hasNextPage,
            hasPrevPage: response.data.pagination.hasPrevPage,
          });
        }
      } else if (response?.data?.courses) {
        setCourses(response.data.courses);
      } else {
        setCourses([]);
      }
    } catch (err) {
      console.error("خطا در دریافت دوره‌ها:", err);
      toast.error("خطا در دریافت دوره‌های آکادمی");
      setCourses([]);
    } finally {
      setIsLoadingCourses(false);
    }
  };

  // بارگذاری اولیه دوره‌ها بعد از دریافت آکادمی
  useEffect(() => {
    if (academyId) {
      fetchCourses(1);
    }
  }, [academyId]);

  // تغییر صفحه
  const handlePageChange = (newPage: number) => {
    if (newPage >= 1 && newPage <= pagination.totalPages) {
      fetchCourses(newPage);
      window.scrollTo({ top: 600, behavior: "smooth" });
    }
  };

  // پردازش تگ‌ها
  const parseTags = (tagString: string): Tag[] => {
    if (!tagString) return [];
    try {
      return JSON.parse(tagString);
    } catch {
      return [];
    }
  };

  const tags = parseTags(academy?.tag as string || "[]");

  if (isLoading) {
    return (
      <Container>
        <div className="flex justify-center items-center min-h-[60vh]">
          <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>
          <p className="mr-4 text-gray-600 dark:text-gray-400">در حال بارگذاری...</p>
        </div>
      </Container>
    );
  }

  if (!academy && !isLoading) {
    return (
      <Container>
        <div className="py-20 text-center">
          <div className="text-6xl mb-4">🏫</div>
          <h2 className="text-2xl font-bold text-gray-800 dark:text-gray-200 mb-2">
            آکادمی یافت نشد
          </h2>
          <p className="text-gray-600 dark:text-gray-400">
            متأسفیم، آکادمی مورد نظر شما وجود ندارد یا حذف شده است.
          </p>
          <button
            onClick={() => router.push("/")}
            className="mt-6 px-6 py-2 bg-pink-500 text-white rounded-lg hover:bg-pink-600 transition-colors"
          >
            بازگشت به صفحه اصلی
          </button>
        </div>
      </Container>
    );
  }

  const academyName = academy?.academy_name || "آکادمی";
  const academyImage = academy?.academy_image 
    ? `${IMAGE_BASE_URL}${academy.academy_image}` 
    : "/images/default-academy.jpg";
  const academyBio = academy?.bio || "این آکادمی هنوز توضیحاتی اضافه نکرده است.";
  const academyRate = academy?.rate || 0;
  const numberOfRate = academy?.number_of_rate || 0;
  const totalCourses = pagination.totalItems;
  const createdAt = academy?.createdAt ? new Date(academy.createdAt).toLocaleDateString("fa-IR") : "نامشخص";


  return (
    <Container >
      {/* هدر حرفه‌ای کامل با تمام اطلاعات */}
      <div className="relative mb-8 ">
        {/* Background Cover with Gradient */}
        <div className="absolute inset-0  rounded-2xl overflow-hidden">
          <div className="absolute inset-0 "></div>
          <div className="absolute inset-0 bg-[url('/images/pattern.png')] opacity-10"></div>
        </div>

        {/* Content */}
        <div className="relative p-6 md:p-8">
          <div className="flex flex-col md:flex-row items-center gap-6 md:gap-8">
            {/* لوگو آکادمی - سمت راست در دسکتاپ */}
            <motion.div
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              transition={{ duration: 0.5 }}
              className="flex-shrink-0"
            >
              <div className="relative w-28 h-28 md:w-32 md:h-32 rounded-2xl overflow-hidden shadow-2xl ">
                <Image
                  src={academyImage}
                  alt={academyName}
                  fill
                  className="object-cover"
                  onError={(e) => {
                    (e.target as HTMLImageElement).src =
                      "/images/default-academy.jpg";
                  }}
                />
              </div>
            </motion.div>

            {/* اطلاعات آکادمی - سمت چپ در دسکتاپ */}
            <motion.div
              initial={{ x: -20, opacity: 0 }}
              animate={{ x: 0, opacity: 1 }}
              transition={{ duration: 0.5, delay: 0.1 }}
              className="flex-1 text-center md:text-right"
            >
              <h1 className="text-2xl md:text-3xl lg:text-4xl font-bold text-white mb-2">
                {academyName}
              </h1>

              {/* توضیحات آکادمی */}
              <p className="text-white/90 leading-relaxed text-sm md:text-base mb-3 max-w-2xl">
                {academyBio}
              </p>

              {/* تگ‌ها */}
              {tags.length > 0 && (
                <div className="flex flex-wrap justify-center md:justify-start gap-2">
                  {tags.map((tag, index) => (
                    <span
                      key={index}
                      className="px-2 py-0.5 bg-white/20 backdrop-blur-sm rounded-full text-xs text-white"
                    >
                      #{tag.value}
                    </span>
                  ))}
                </div>
              )}

             
            </motion.div>
          </div>
        </div>
      </div>

      {/* کارت‌های آمار جزئی */}
      <motion.div
        initial={{ y: 20, opacity: 0 }}
        animate={{ y: 0, opacity: 1 }}
        transition={{ duration: 0.5, delay: 0.2 }}
        className="grid p-3 grid-cols-2 md:grid-cols-4 gap-4 mb-8 -mt-6 relative z-10"
      >
        <div className="bg-white dark:bg-neutral-800 rounded-xl p-4 shadow-lg text-center hover:shadow-xl transition-shadow">
          <div className="text-3xl mb-2">📚</div>
          <div className="text-2xl font-bold text-gray-800 dark:text-gray-100">
            {totalCourses}
          </div>
          <div className="text-sm text-gray-500">دوره آموزشی</div>
        </div>

        <div className="bg-white dark:bg-neutral-800 rounded-xl p-4 shadow-lg text-center hover:shadow-xl transition-shadow">
          <div className="text-3xl mb-2">📅</div>
          <div className="text-2xl font-bold text-gray-800 dark:text-gray-100">
            {createdAt || "جدید"}
          </div>
          <div className="text-sm text-gray-500">تاسیس</div>
        </div>
      </motion.div>

      {/* لیست دوره‌ها */}
      <motion.section
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        transition={{ duration: 0.3, delay: 0.3 }}
        className="p-3"
      >
        <div className="flex justify-between items-center mb-6">
          <h2 className="text-xl font-bold text-gray-800 dark:text-gray-100">
            📚 دوره‌های آموزشی
          </h2>
          <span className="text-sm text-gray-500">{totalCourses} دوره</span>
        </div>

        {courses.length === 0 ? (
          <div className="text-center py-12 bg-gray-50 dark:bg-gray-800/50 rounded-2xl">
            <div className="text-6xl mb-4">📚</div>
            <p className="text-gray-600 dark:text-gray-400">
              هنوز دوره‌ای برای این آکادمی ثبت نشده است.
            </p>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            {courses.map((course, index) => (
              <motion.div
                key={course._id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: index * 0.05 }}
              >
                <Link
                  href={`/academy/${course._id}/course`}
                  className="group block bg-white dark:bg-neutral-800 rounded-xl overflow-hidden shadow-md hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1"
                >
                  <div className="relative h-48 w-full overflow-hidden">
                    <Image
                      src={
                        course.course_image
                          ? `${IMAGE_BASE_URL}${course.course_image}`
                          : "/images/default-course.jpg"
                      }
                      alt={course.cuorse_name}
                      fill
                      className="object-cover group-hover:scale-110 transition-transform duration-500"
                    />
                    <div className="absolute inset-0 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                    {course.offer && parseInt(course.offer) > 0 && (
                      <div className="absolute top-2 right-2 bg-red-500 text-white text-xs font-bold px-2 py-1 rounded-full z-10">
                        🔥 {course.offer}% تخفیف
                      </div>
                    )}
                  </div>

                  <div className="p-4">
                    <h3 className="font-bold text-lg text-gray-800 dark:text-gray-100 mb-1 line-clamp-1">
                      {course.cuorse_name}
                    </h3>
                    <p className="text-sm text-gray-500 dark:text-gray-400 mb-3 line-clamp-1">
                      {course.caption}
                    </p>

                    <div className="flex justify-between items-center mt-3 pt-3 border-t border-gray-100 dark:border-gray-700">
                      <div className="flex items-center gap-1 text-sm text-gray-500">
                        <span>👨‍🏫</span>
                        <span>{course.teacher_name}</span>
                      </div>
                      <div className="text-lg font-bold text-pink-500">
                        {course.offer && parseInt(course.offer) > 0 ? (
                          <>
                            <span className="line-through text-xs text-gray-400 ml-1">
                              {parseInt(course.price).toLocaleString()}
                            </span>
                            {(
                              (parseInt(course.price) *
                                (100 - parseInt(course.offer))) /
                              100
                            ).toLocaleString()}
                          </>
                        ) : (
                          parseInt(course.price).toLocaleString()
                        )}
                        <span className="text-xs"> تومان</span>
                      </div>
                    </div>
                  </div>
                </Link>
              </motion.div>
            ))}
          </div>
        )}
      </motion.section>
    </Container>
  );
}

export default AcademyPage;
