"use client"

import { useEffect, useState } from "react"
import { BookOpen, ChevronLeft } from "lucide-react"

import Link from "@/components/common/versioned-link"
import SafeImage from "@/components/common/safe-img"
import { ApiEndpoint } from "@/lib/services/api.service"
import { useApi } from "@/lib/services/axios.service"
import { CourseCardDto } from "@/lib/dto/catalogue.dto"
import { faNumber } from "@/lib/helpers/format.helper"

/** How many courses the strip shows; the rest are on /my-courses. */
const SHOWN = 6

export default function MyCoursesStrip() {
  const [courses, setCourses] = useState<CourseCardDto[]>([])
  const [total, setTotal] = useState(0)
  const [, fetchCourses] = useApi<CourseCardDto[]>({ url: ApiEndpoint("catalogue", "courses"), method: "GET" })

  useEffect(() => {
    fetchCourses({ params: { mine: 1, per_page: SHOWN } }).then(
      (response) => {
        setCourses(response?.body?.data ?? [])
        setTotal(response?.body?.meta?.total ?? 0)
      },
      () => setCourses([]),
    )
  }, [fetchCourses])

  if (courses.length === 0) return null

  return (
    <section className="bg-canvas border border-line rounded-card shadow-card p-3.5">
      <div className="flex items-center justify-between mb-3">
        <h2 className="text-title-3 font-extrabold flex items-center gap-1.5">
          <BookOpen className="w-4 h-4 text-sienna" aria-hidden="true" />
          دوره‌های من
          <span className="text-caption font-bold text-ink-soft">({faNumber(total)})</span>
        </h2>
        <Link href="/my-courses" aria-label="همه: دوره‌های من" className="flex items-center h-11 -my-2.5 px-2 -mx-2 text-caption font-bold text-sienna">
          همه
          <ChevronLeft className="w-4 h-4" aria-hidden="true" />
        </Link>
      </div>

      <div className="flex overflow-x-auto no-scrollbar -mx-3.5 px-3.5 [&>*:not(:last-child)]:ml-2.5">
        {courses.map((course) => (
          <Link key={course.id} href={`/course/detail?id=${course.id}`} className="w-[132px] shrink-0">
            <span className="relative block aspect-[4/3] rounded-xl overflow-hidden bg-paper-2">
              <SafeImage src={course.cover} />
            </span>
            <span className="block text-body-sm font-bold mt-1.5 truncate">{course.title}</span>
            {course.progress_percent !== null && (
              <span className="flex items-center mt-1">
                <span className="flex-1 h-1 rounded-full bg-paper-2 overflow-hidden">
                  <span
                    className={`block h-full rounded-full ${course.progress_percent >= 100 ? "bg-sage" : "bg-sienna"}`}
                    style={{ width: `${course.progress_percent}%` }}
                  />
                </span>
                <span className="text-micro text-ink-soft mr-1.5">{faNumber(course.progress_percent)}٪</span>
              </span>
            )}
          </Link>
        ))}
      </div>
    </section>
  )
}
