"use client"

import { useState, useEffect } from "react"
import { useParams } from "next/navigation"
import { useTranslation } from "react-i18next"
import { Loader2 } from "lucide-react"
import { Progress } from "@/components/ui/progress"
import { CourseTabs } from "@/components/student/courses/course-tabs"
import { UpcomingClass } from "@/components/student/courses/upcoming-class"
import { getCourses } from "@/services/courses/query"
import { getClassSessions } from "@/services/class_sessions/query"
import { getClassMaterials } from "@/services/class_materials/query"
import { getCoursePackageStudents } from "@/services/course_package_students/query"

export default function CourseDetailPage() {
  const { t } = useTranslation()
  const params = useParams()
  const courseId = Number.parseInt(params.id as string)

  const [loading, setLoading] = useState(true)
  const [course, setCourse] = useState(null)
  const [sessions, setSessions] = useState([])
  const [nextSession, setNextSession] = useState(null)
  const [materials, setMaterials] = useState([])
  const [progress, setProgress] = useState({
    overall: 0,
    sessions: [],
  })

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)

        // Fetch course details
        const coursesData = await getCourses()
        const courseData = coursesData.find((c) => c.id === courseId)

        if (!courseData) {
          throw new Error("Course not found")
        }

        setCourse(courseData)

        // Fetch sessions
        const sessionsData = await getClassSessions()
        const courseSessionsData = sessionsData.filter((s) => s.course_package_id === courseId)

        // Map the session data to the format expected by the component
        const mappedSessions = courseSessionsData.map((session) => ({
          id: session.id,
          title: session.title,
          date: session.scheduled_at || session.start_time, // Use new field with fallback
          attended: Math.random() > 0.3, // Mock attendance data
          start_time: session.scheduled_at || session.start_time, // Use new field with fallback
          end_time: session.end_time, // Calculate end time based on duration if needed
          instructor_name: session.instructor_name,
          location: session.offline_location || session.online_meeting_link || session.location, // Use new fields with fallback
          meeting_link: session.online_meeting_link || session.meeting_link, // Use new field with fallback
        }))

        setSessions(mappedSessions)

        // Find next upcoming session
        const now = new Date()
        const upcomingSessions = mappedSessions
          .filter((session) => new Date(session.start_time) > now)
          .sort((a, b) => new Date(a.start_time) - new Date(b.start_time))

        if (upcomingSessions.length > 0) {
          const nextSessionData = upcomingSessions[0]
          setNextSession({
            id: nextSessionData.id,
            title: nextSessionData.title,
            start_time: nextSessionData.start_time,
            end_time: nextSessionData.end_time,
            instructor_name: nextSessionData.instructor_name,
            meeting_link: nextSessionData.meeting_link,
            course_id: courseId,
            course_title: courseData.title,
          })
        }

        // Fetch materials
        const materialsData = await getClassMaterials()
        // In a real app, we would join with sessions to get materials for this course
        // For now, we'll simulate this with the mock data
        const courseSessionIds = mappedSessions.map((session) => session.id)
        const courseMaterialsData = materialsData.filter((m) => courseSessionIds.includes(m.session_id))
        setMaterials(courseMaterialsData)

        // Fetch student progress
        const studentId = 1 // Mock current student ID
        const enrollments = await getCoursePackageStudents(studentId)
        const enrollment = enrollments.find((e) => e.course_package_id === courseId)

        if (enrollment) {
          // Map sessions to progress data
          const sessionsProgress = mappedSessions.map((session) => ({
            id: session.id,
            title: session.title,
            date: session.start_time,
            attended: session.attended,
          }))

          setProgress({
            overall: enrollment.progress || 0,
            sessions: sessionsProgress,
          })
        }
      } catch (error) {
        console.error("Error fetching course details:", error)
      } finally {
        setLoading(false)
      }
    }

    if (courseId) {
      fetchData()
    }
  }, [courseId])

  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <Loader2 className="h-8 w-8 animate-spin text-secondary" />
      </div>
    )
  }

  if (!course) {
    return (
      <div className="text-center py-12">
        <h2 className="text-2xl font-bold text-gray-900 mb-2">{t("student.courseNotFound")}</h2>
        <p className="text-gray-600 mb-6">{t("student.courseNotFoundDescription")}</p>
        <a
          href="/student/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"
        >
          {t("student.backToCourses")}
        </a>
      </div>
    )
  }

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-gray-900 mb-2">{course.title}</h1>
        <p className="text-gray-600 mb-6">{course.description}</p>

        <div className="bg-white rounded-lg border p-4 mb-6">
          <div className="flex justify-between items-center mb-2">
            <span className="text-sm text-gray-500">{t("student.courseProgress")}</span>
            <span className="text-sm font-medium">{progress.overall}%</span>
          </div>
          <Progress value={progress.overall} className="h-2" />
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
          <div className="bg-white rounded-lg border p-4">
            <p className="text-sm text-gray-500 mb-1">{t("student.instructor")}</p>
            <p className="font-medium">{course.instructor_name}</p>
          </div>
          <div className="bg-white rounded-lg border p-4">
            <p className="text-sm text-gray-500 mb-1">{t("student.duration")}</p>
            <p className="font-medium">{course.duration}</p>
          </div>
          <div className="bg-white rounded-lg border p-4">
            <p className="text-sm text-gray-500 mb-1">{t("student.totalSessions")}</p>
            <p className="font-medium">{sessions.length}</p>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2">
          <CourseTabs courseId={courseId} sessions={sessions} materials={materials} progress={progress} />
        </div>

        <div>
          {nextSession ? (
            <UpcomingClass session={nextSession} />
          ) : (
            <div className="bg-white rounded-lg border p-6 text-center">
              <h3 className="text-lg font-medium text-gray-900 mb-2">{t("student.noUpcomingClasses")}</h3>
              <p className="text-gray-500 text-sm">{t("student.allSessionsCompleted")}</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"
            >
              {t("student.viewAllSessions")}
            </a>
          </div>
        </div>
      </div>
    </div>
  )
}
