"use client"

import { useState, useEffect } from "react"
import { Loader2 } from "lucide-react"
import { CourseProgressCard } from "@/components/student/courses/course-progress-card"
import { SortDropdown } from "@/components/student/courses/sort-dropdown"
import { UpcomingClass } from "@/components/student/courses/upcoming-class"
import { getSubscribedCourses, getUpcomingSessions } from "@/services/students/query"
import { GetCourseProgressResponse, getCoursesProgress } from "@/services/student_page/query"


export default function StudentCoursesPage() {
  const [loading, setLoading] = useState(true)
  const [courses, setCourses] = useState([])
  const [nextSession, setNextSession] = useState(null)
  const [sortOption, setSortOption] = useState("next-class") // 'next-class' or 'progress'
  const [courseProgress, setCourseProgress] = useState<GetCourseProgressResponse>()

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)
        console.log("[courses] Fetching student courses and sessions...")

        // Fetch subscribed courses and upcoming sessions
        const [coursesData, sessionsData, courseProgress] = await Promise.all([getSubscribedCourses(), getUpcomingSessions(), getCoursesProgress()])

        console.log("[courses] Courses data:", { count: coursesData.length })
        console.log("[courses] Sessions data:", { count: sessionsData.length })

        // Process courses data - add progress and next class info
        const processedCourses = coursesData.map((course) => {
          // Find the next session for this course
          const courseSession = sessionsData.find(
            (session) =>
              session.package_class?.course_package?.course?.id === course.id || session.course_id === course.id,
          )

          let progress = 0
          try{
            const package_id = courseProgress.course_package_taken[course.id];

             progress = courseProgress.total_sessions[package_id]
              ? Math.round((courseProgress.attended_sessions[package_id] || 0) / courseProgress.total_sessions[package_id] * 100)
              : 0
          }
          catch (e) {
             progress = 0;
          }
          

          return {
            ...course,
            progress: progress, //course.progress || Math.floor(Math.random() * 100), // Use actual progress or mock
            nextClass: courseSession?.scheduled_at || null,
            nextClassTitle: courseSession?.package_class?.title || null,
            instructor: courseSession?.instructor || null,
          }
        })

        // Sort courses based on selected option
        const sortedCourses = sortCourses(processedCourses, sortOption)
        setCourses(sortedCourses)

        // Find the next upcoming session across all courses
        if (sessionsData.length > 0) {
          const nextSessionData = sessionsData[0] // Already sorted by date in the service

          setNextSession({
            id: nextSessionData.id,
            title: nextSessionData.package_class?.title || nextSessionData.title || "Class Session",
            start_time: nextSessionData.scheduled_at,
            end_time: nextSessionData.end_time || nextSessionData.scheduled_at,
            instructor_name: nextSessionData.instructor?.name || "TBA",
            meeting_link: nextSessionData.meeting_link,
            course_id: nextSessionData.package_class?.course_package?.course?.id || nextSessionData.course_id,
            course_title: nextSessionData.package_class?.course_package?.course?.title || "Course",
          })
        }
      } catch (error) {
        console.error("[courses] Error fetching courses:", error)
      } finally {
        setLoading(false)
      }
    }

    fetchData()
  }, [])

  // Re-sort when sort option changes
  useEffect(() => {
    if (courses.length > 0) {
      const sortedCourses = sortCourses(courses, sortOption)
      setCourses(sortedCourses)
    }
  }, [sortOption])

  const sortCourses = (coursesToSort, option) => {
    if (option === "progress") {
      return [...coursesToSort].sort((a, b) => b.progress - a.progress)
    } else if (option === "next-class") {
      return [...coursesToSort].sort((a, b) => {
        if (!a.nextClass) return 1
        if (!b.nextClass) return -1
        return new Date(a.nextClass) - new Date(b.nextClass)
      })
    }
    return coursesToSort
  }

  const handleSortChange = (option) => {
    setSortOption(option)
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-4 md:mb-0">{"My Courses"}</h1>
        <SortDropdown value={sortOption} onChange={handleSortChange} />
      </div>

      {loading ? (
        <div className="flex justify-center items-center h-64">
          <Loader2 className="h-8 w-8 animate-spin text-secondary" />
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
          <div className="lg:col-span-2">
            {courses.length > 0 ? (
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                {courses.map((course) => (
                  <CourseProgressCard key={course.id} course={course} />
                ))}
              </div>
            ) : (
              <div className="bg-gray-50 rounded-lg p-8 text-center">
                <h3 className="text-xl font-medium text-gray-900 mb-2">{"No Courses Enrolled"}</h3>
                <p className="text-gray-600 mb-4">
                  {"Browse our available courses to get started with your learning journey."}
                </p>
                <a
                  href="/courses"
                  className="inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-secondary hover:bg-secondary-dark focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-secondary"
                >
                  {"Browse Courses"}
                </a>
              </div>
            )}
          </div>

          <div>
            {nextSession ? (
              <UpcomingClass session={nextSession} />
            ) : (
              <div className="bg-gray-50 rounded-lg p-6 text-center">
                <h3 className="text-lg font-medium text-gray-900 mb-2">{"No Upcoming Classes"}</h3>
                <p className="text-gray-500 text-sm">{"Check back later for scheduled sessions."}</p>
              </div>
            )}

            <div className="mt-6">
              <a
                href="/student/sessions"
                className="block w-full text-center py-2 px-4 border border-gray-300 rounded-md text-sm font-medium text-gray-700 hover:bg-gray-50"
              >
                {"View All Sessions"}
              </a>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
