"use client"

import { useEffect, useState } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Calendar, BookOpen, CheckCircle2 } from "lucide-react"
import Image from "next/image"
import Link from "next/link"
import { getSubscribedCourses, getUpcomingSessions, getStudentOrders } from "@/services/students/query"

import { getCourses } from "@/services/courses/query"

import { getCoursePackages } from "@/services/course_packages/query"
import { getNotifications } from "@/services/notifications/query"
import type { Course, ClassSession, Order, CoursePackage, Notification } from "@/services/types"
import { orderItemToString } from "@/services/utils"

export default function StudentDashboard() {
  const router = useRouter()
  const [isClient, setIsClient] = useState(false)
  const [userInfo, setUserInfo] = useState<any>(null)
  const [enrolledCourses, setEnrolledCourses] = useState<Course[]>([])
  const [isLoadingCourses, setIsLoadingCourses] = useState(false)
  const [courseError, setCourseError] = useState<string | null>(null)
  const [upcomingSessions, setUpcomingSessions] = useState<ClassSession[]>([])
  const [isLoadingSessions, setIsLoadingSessions] = useState(false)
  const [sessionError, setSessionError] = useState<string | null>(null)
  const [orders, setOrders] = useState<Order[]>([])
  const [isLoadingOrders, setIsLoadingOrders] = useState(false)
  const [orderError, setOrderError] = useState<string | null>(null)
  const [courses, setCourses] = useState<Course[]>([])
  const [coursePackages, setCoursePackages] = useState<CoursePackage[]>([])
  const [notifications, setNotifications] = useState<Notification[]>([])
  const [isLoadingNotifications, setIsLoadingNotifications] = useState(false)
  const [notificationError, setNotificationError] = useState<string | null>(null)

  // Check if user is logged in
  useEffect(() => {
    setIsClient(true)
    const loginInfo = localStorage.getItem("login_info")

    if (!loginInfo) {
      router.push("/login")
      return
    }

    const parsedInfo = JSON.parse(loginInfo)

    if (!parsedInfo.logged_in_status || !parsedInfo.roles.includes("student")) {
      router.push("/login")
      return
    }

    setUserInfo(parsedInfo)
  }, [router])

  // Add this useEffect to fetch courses
  useEffect(() => {
    async function fetchCourses() {
      try {
        setIsLoadingCourses(true)
        setCourseError(null)
        const courses = await getSubscribedCourses()
        setEnrolledCourses(courses)
      } catch (error) {
        console.error("Error fetching courses:", error)
        setCourseError("Failed to load courses. Please try again later.")
      } finally {
        setIsLoadingCourses(false)
      }
    }

    fetchCourses()
  }, [])

  // Fetch upcoming sessions
  useEffect(() => {
    async function fetchSessions() {
      try {
        setIsLoadingSessions(true)
        setSessionError(null)
        const sessions = await getUpcomingSessions()
        setUpcomingSessions(sessions)
      } catch (error) {
        console.error("Error fetching sessions:", error)
        setSessionError("Failed to load sessions. Please try again later.")
      } finally {
        setIsLoadingSessions(false)
      }
    }

    fetchSessions()
  }, [])

  // Fetch orders and reference data
  useEffect(() => {
    async function fetchOrdersAndReferenceData() {
      try {
        setIsLoadingOrders(true)
        setOrderError(null)

        // Fetch orders and reference data in parallel
        const [ordersData, coursesData, packagesData] = await Promise.all([
          getStudentOrders(),
          getCourses(),
          getCoursePackages()
        ])

        setOrders(ordersData)
        setCourses(coursesData)
        setCoursePackages(packagesData)
      } catch (error) {
        console.error("Error fetching orders:", error)
        setOrderError("Failed to load payment history. Please try again later.")
      } finally {
        setIsLoadingOrders(false)
      }
    }

    if (userInfo) {
      fetchOrdersAndReferenceData()
    }
  }, [userInfo])

  // Fetch notifications
  useEffect(() => {
    async function fetchNotifications() {
      try {
        setIsLoadingNotifications(true)
        setNotificationError(null)
        const notificationsData = await getNotifications()
        setNotifications(notificationsData)
      } catch (error) {
        console.error("Error fetching notifications:", error)
        setNotificationError("Failed to load notifications. Please try again later.")
      } finally {
        setIsLoadingNotifications(false)
      }
    }

    fetchNotifications()
  }, [])

  // Format date to readable format
  const formatDate = (dateString: string) => {
    const date = new Date(dateString)
    return date.toLocaleDateString("en-US", {
      weekday: "short",
      month: "short",
      day: "numeric",
      year: "numeric",
    })
  }

  // Format time to readable format
  const formatTime = (dateString: string) => {
    const date = new Date(dateString)
    return date.toLocaleTimeString("en-US", {
      hour: "2-digit",
      minute: "2-digit",
    })
  }

  // Calculate if a session is happening soon (within 30 minutes)
  const isSessionSoon = (dateString: string) => {
    const sessionDate = new Date(dateString)
    const now = new Date()
    const diffMs = sessionDate.getTime() - now.getTime()
    const diffMins = Math.round(diffMs / 60000)
    return diffMins > 0 && diffMins <= 30
  }

  // Get unread notifications count
  const unreadNotificationsCount = notifications.filter((n) => !n.read).length

  // Helper function to get course title by ID
  const getCourseTitle = (courseId: number): string => {
    const course = courses.find((c) => c.id === courseId)
    return course?.title || "Unknown Course"
  }

  // Helper function to get course package title by ID
  const getCoursePackageTitle = (packageId: number): string => {
    const coursePackage = coursePackages.find((cp) => cp.id === packageId)
    return coursePackage?.name || "Unknown Package"
  }

  // Helper function to get total paid amount for an order
  const getTotalPaid = (order: Order): string => {
    if (order.payments && order.payments.length > 0) {
      const totalPaid = order.payments
        .filter((payment) => payment.status === "paid")
        .reduce((sum, payment) => sum + Number.parseFloat(payment.amount_paid), 0)
      return `$${totalPaid.toFixed(2)}`
    }
    return `$${Number.parseFloat(order.final_amount).toFixed(2)}`
  }

  // Helper function to get payment status
  const getPaymentStatus = (order: Order): string => {
    return order.payment_status.charAt(0).toUpperCase() + order.payment_status.slice(1)
  }

  const WEBSITE_BASE_URL = process.env.NEXT_PUBLIC_WEBSITE_BASE_URL || ""


  if (!isClient || !userInfo) {
    return null // Prevent hydration errors
  }

  return (
    <div className="container py-8">
      <div className="mb-6">
        <h1 className="text-3xl font-bold font-heading mb-2">Welcome back, {userInfo.email.split("@")[0]}!</h1>
        <p className="text-gray-600">Here's an overview of your learning progress.</p>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
        <Card className="border-0 bg-secondary-light">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">Courses in Progress</p>
                <h3 className="text-2xl font-bold">{enrolledCourses.length}</h3>
              </div>
              <div className="h-12 w-12 rounded-full bg-primary-light flex items-center justify-center">
                <BookOpen className="h-6 w-6 text-secondary" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="border-0 bg-secondary-light">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">Upcoming Sessions</p>
                <h3 className="text-2xl font-bold">{upcomingSessions.length}</h3>
              </div>
              <div className="h-12 w-12 rounded-full bg-primary-light flex items-center justify-center">
                <Calendar className="h-6 w-6 text-secondary" />
              </div>
            </div>
          </CardContent>
        </Card>

        <Card className="border-0 bg-secondary-light">
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-500">Completed Courses</p>
                <h3 className="text-2xl font-bold">0</h3>
              </div>
              <div className="h-12 w-12 rounded-full bg-primary-light flex items-center justify-center">
                <CheckCircle2 className="h-6 w-6 text-secondary" />
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* Tabs */}
      <Tabs defaultValue="courses" className="mb-6">
        <TabsList className="mb-6">
          <TabsTrigger value="courses">My Courses</TabsTrigger>
          <TabsTrigger value="calendar">Calendar</TabsTrigger>
          <TabsTrigger value="payments">Payments</TabsTrigger>
        </TabsList>

        <TabsContent value="courses" className="space-y-6">
          <h2 className="text-2xl font-bold font-heading mb-4">My Courses</h2>

          {isLoadingCourses && (
            <div className="flex justify-center py-8">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-secondary"></div>
            </div>
          )}

          {courseError && <div className="bg-red-50 text-red-700 p-4 rounded-md">{courseError}</div>}

          {!isLoadingCourses && !courseError && enrolledCourses.length === 0 && (
            <div className="text-center py-8 bg-gray-50 rounded-lg">
              <BookOpen className="mx-auto h-12 w-12 text-gray-400" />
              <h3 className="mt-2 text-lg font-medium">No courses enrolled</h3>
              <p className="mt-1 text-gray-500">Browse our catalog to find courses that interest you.</p>
              <Button className="mt-4">Browse Courses</Button>
            </div>
          )}

          {/* Course Cards */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {enrolledCourses.map((course) => (
              <Card key={course.id} className="overflow-hidden border-0">
                <div className="relative h-40">
                  <Image src={course.image || "/placeholder.svg"} alt={course.title} fill className="object-cover" />
                </div>
                <CardContent className="p-6">
                  <h3 className="text-xl font-bold mb-2 font-heading">{course.title}</h3>
                  <p className="text-sm text-gray-500 mb-4 line-clamp-2">{course.description}</p>
                  {false && (
                    <>
                    <div className="flex justify-between text-sm text-gray-500 mb-2">
                    <span>Price: ${Number.parseFloat(course.price).toFixed(2)}</span>
                  </div>
                  <Button className="w-full">Continue Learning</Button>
                    </>
                  )}
                  
                </CardContent>
              </Card>
            ))}
          </div>

          <div className="text-center mt-8">
            {false && (
              <Link href="/student/courses" className="text-secondary hover:text-secondary-dark underline">
              View All Courses
            </Link>
            )}

            <a href={`${WEBSITE_BASE_URL}/courses`} className="text-secondary hover:text-secondary-dark underline">
              View All Courses
            </a>
          </div>
        </TabsContent>

        <TabsContent value="calendar" className="space-y-6">
          <h2 className="text-2xl font-bold font-heading mb-4">Upcoming Sessions</h2>

          <Card className="border-0 bg-secondary-light">
            <CardContent className="p-6">
              {isLoadingSessions && (
                <div className="flex justify-center py-8">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-secondary"></div>
                </div>
              )}

              {sessionError && <div className="bg-red-50 text-red-700 p-4 rounded-md">{sessionError}</div>}

              {!isLoadingSessions && !sessionError && upcomingSessions.length === 0 && (
                <div className="text-center py-8 bg-gray-50 rounded-lg">
                  <Calendar className="mx-auto h-12 w-12 text-gray-400" />
                  <h3 className="mt-2 text-lg font-medium">No upcoming sessions</h3>
                  <p className="mt-1 text-gray-500">Your upcoming sessions will appear here.</p>
                </div>
              )}

              <div className="space-y-6">
                {upcomingSessions.map((session) => (
                  <div
                    key={session.id}
                    className="flex items-start gap-4 pb-4 border-b border-gray-200 last:border-0 last:pb-0"
                  >
                    <div className="h-12 w-12 rounded-full bg-primary-light flex items-center justify-center shrink-0">
                      <Calendar className="h-6 w-6 text-secondary" />
                    </div>
                    <div>
                      <h3 className="font-bold">
                        {session.package_class?.course_package?.course?.title || "Course Title"}
                      </h3>
                      <p className="text-gray-600 font-medium">{session.package_class?.title || "Class Title"}</p>
                      <p className="text-gray-600">
                        {formatDate(session.scheduled_at)} • {formatTime(session.scheduled_at)}
                      </p>
                      <p className="text-sm text-gray-500">
                        Instructor: {session.instructor?.name || "Instructor Name"}
                      </p>
                    </div>
                    <Button variant="outline" className="ml-auto shrink-0">
                      {isSessionSoon(session.scheduled_at) && session.online_meeting_link
                        ? "Join Session"
                        : "View Details"}
                    </Button>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>

          <div className="text-center mt-8">
            <Link href="/student/calendar" className="text-secondary hover:text-secondary-dark underline">
              View Full Calendar
            </Link>
          </div>
        </TabsContent>

        <TabsContent value="payments" className="space-y-6">
          <h2 className="text-2xl font-bold font-heading mb-4">Payment History</h2>

          <Card className="border-0 bg-secondary-light">
            <CardContent className="p-6">
              {isLoadingOrders && (
                <div className="flex justify-center py-8">
                  <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-secondary"></div>
                </div>
              )}

              {orderError && <div className="bg-red-50 text-red-700 p-4 rounded-md">{orderError}</div>}

              {!isLoadingOrders && !orderError && orders.length === 0 && (
                <div className="text-center py-8 bg-gray-50 rounded-lg">
                  <CheckCircle2 className="mx-auto h-12 w-12 text-gray-400" />
                  <h3 className="mt-2 text-lg font-medium">No payment history</h3>
                  <p className="mt-1 text-gray-500">Your payment history will appear here.</p>
                </div>
              )}

              <div className="space-y-6">
                {orders.map((order) => (
                  <div
                    key={order.id}
                    className="flex items-center justify-between pb-4 border-b border-gray-200 last:border-0 last:pb-0"
                  >
                    <div>
                      {order.items?.map((item, itemIndex) => (
                        <div key={itemIndex} className="mb-2 last:mb-0"
                         dangerouslySetInnerHTML={{
                      __html: orderItemToString(item),
                    }}
                        >

                          
                        </div>
                      ))}
                      <p className="text-sm text-gray-500">{new Date(order.created_at).toLocaleDateString()}</p>
                    </div>
                    <div className="text-right">
                      <p className="font-bold">{getTotalPaid(order)}</p>
                      <span
                        className={`inline-block px-2 py-1 text-xs rounded-full ${
                          order.payment_status === "paid"
                            ? "bg-green-100 text-green-800"
                            : order.payment_status === "pending"
                              ? "bg-yellow-100 text-yellow-800"
                              : "bg-red-100 text-red-800"
                        }`}
                      >
                        {getPaymentStatus(order)}
                      </span>
                    </div>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>

          <div className="text-center mt-8">
            <Link href="/student/payments" className="text-secondary hover:text-secondary-dark underline">
              View All Transactions
            </Link>
          </div>
        </TabsContent>
      </Tabs>

      {/* Notifications Section */}
      <div className="mt-8">
        <h2 className="text-2xl font-bold font-heading mb-4">Recent Notifications</h2>
        <Card className="border-0 bg-secondary-light">
          <CardContent className="p-6">
            {isLoadingNotifications && (
              <div className="flex justify-center py-8">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-secondary"></div>
              </div>
            )}

            {notificationError && <div className="bg-red-50 text-red-700 p-4 rounded-md">{notificationError}</div>}

            <div className="space-y-4">
              {notifications.slice(0, 3).map((notification) => (
                <div
                  key={notification.id}
                  className={`p-3 rounded-lg ${
                    notification.read ? "bg-gray-50" : "bg-blue-50 border-l-4 border-blue-500"
                  }`}
                >
                  <div className="flex items-start">
                    <div className={`rounded-full p-2 mr-3 ${notification.color}`}>
                      {notification.type === "material" ? (
                        <BookOpen className={`h-4 w-4 ${notification.iconColor}`} />
                      ) : notification.type === "schedule" ? (
                        <Calendar className={`h-4 w-4 ${notification.iconColor}`} />
                      ) : (
                        <CheckCircle2 className={`h-4 w-4 ${notification.iconColor}`} />
                      )}
                    </div>
                    <div>
                      <h5 className="font-medium text-secondary text-sm">{notification.title}</h5>
                      <p className="text-xs text-gray-600 mt-1">{notification.message}</p>
                      <p className="text-xs text-gray-400 mt-2">
                        {new Date(notification.date).toLocaleDateString()} •{" "}
                        {new Date(notification.date).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}
                      </p>
                    </div>
                  </div>
                </div>
              ))}
            </div>
            {unreadNotificationsCount > 0 && (
              <div className="mt-4 text-center">
                <Link href="/student/notifications" className="text-secondary hover:text-secondary-dark underline">
                  View {unreadNotificationsCount} unread notification{unreadNotificationsCount > 1 ? "s" : ""}
                </Link>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
