"use client";

import { Course } from "@/types/types";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Edit, Trash2, Video, Clock, DollarSign, Highlighter, ChevronLeft, ChevronRight } from "lucide-react";
import Image from "next/image";
import { IMAGE_BASE_URL, buildStorageUrl } from "../main/BaseUrl";
import PageLoader from "@/components/ui/PageLoader";

interface CourseListProps {
  courses: Course[];
  onEdit: (course: Course) => void;
  onVideo: (course: Course) => void;
  onPro: (courseId: string) => void;
  onDelete: (_id: string) => void;
  currentPage?: number;
  totalPages?: number;
  totalCourses?: number;
  onPageChange?: (page: number) => void;
  isLoading?: boolean;
}

export function CourseList({ 
  courses, 
  onEdit, 
  onDelete, 
  onVideo, 
  onPro,
  currentPage = 1,
  totalPages = 1,
  totalCourses = 0,
  onPageChange,
  isLoading = false
}: CourseListProps) {
  
  // اگر در حال لودینگ است
  if (isLoading) {
    return <PageLoader label="در حال بارگذاری…" />;
  }

  // اگر هیچ دوره‌ای وجود ندارد
  if (!courses || courses.length === 0) {
    return (
      <div className="text-center py-12">
        <p className="text-muted-foreground">هیچ پکیجی یافت نشد</p>
      </div>
    );
  }

  return (
    <div dir="rtl" className="space-y-6">
      {/* نمایش تعداد کل دوره‌ها */}
      <div className="text-sm text-muted-foreground">
        نمایش {courses.length} مورد از {totalCourses} پکیج
      </div>

      {/* گرید دوره‌ها */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {courses.map((course, index) => (
          <Card key={course._id || index} className={`overflow-hidden hover:shadow-lg transition-shadow ${course.type === "pro" ? "shadow-lg shadow-[#FF107D] border-2 border-[#FF107D]" : ""}`}>
            <div className="relative h-48 w-full">
              <Image
                src={IMAGE_BASE_URL + course.course_image}
                alt={course.cuorse_name}
                fill
                className="object-cover"
                onError={(e) => {
                  (e.target as HTMLImageElement).src = "/placeholder.jpg";
                }}
              />
              {course.offer && parseInt(course.offer) > 0 && (
                <Badge className="absolute top-2 right-2 bg-red-500">
                  {course.offer}% تخفیف
                </Badge>
              )}
            </div>
            
            <CardHeader>
              <CardTitle className="text-lg">{course.cuorse_name || course.name}</CardTitle>
              <p className="text-sm text-muted-foreground">
                مدرس: {course.teacher_name || course.instructor}
              </p>
            </CardHeader>
            
            <CardContent className="space-y-3">
              <div className="flex justify-between items-center">
                <div className="flex items-center gap-1">
                  <Video className="w-4 h-4" />
                  <span className="text-sm">{course.number_of_course_content || course.videoCount || 0} ویدیو</span>
                </div>
                <div className="flex items-center gap-1">
                  <Clock className="w-4 h-4" />
                  <span className="text-sm">{course.course_time || course.duration || "0 ساعت"}</span>
                </div>
                <div className="flex items-center gap-1">
                  <DollarSign className="w-4 h-4" />
                  <span className="text-sm font-bold">
                    {course.offer && parseInt(course.offer) > 0 ? (
                      <>
                        <span className="line-through text-muted-foreground text-xs">
                          {parseInt(course.price).toLocaleString()}
                        </span>
                        {" "}
                        {(
                          (parseInt(course.price) * (100 - parseInt(course.offer))) / 100
                        ).toLocaleString()}
                      </>
                    ) : (
                      parseInt(course.price).toLocaleString()
                    )}
                  </span>
                </div>
              </div>
              
              <p className="text-sm text-muted-foreground line-clamp-2">
                {course.caption}
              </p>
              
              <div className="flex gap-2 pt-2">
                <Button
                  variant="outline"
                  size="sm"
                  className="flex-1"
                  onClick={() => onEdit(course)}
                >
                  <Edit className="w-4 h-4 ml-1" />
                  ویرایش
                </Button>
                <Button
                  variant="destructive"
                  size="sm"
                  className="flex-1"
                  onClick={() => onDelete(course._id)}
                >
                  <Trash2 className="w-4 h-4 ml-1" />
                  حذف
                </Button>
              </div>
              <div className="flex gap-2 pt-2">
                <Button
                  variant="default"
                  size="sm"
                  className="flex-1"
                  onClick={() => onVideo(course)}
                >
                  <Video className="w-4 h-4 ml-1" />
                  ویدیو
                </Button>
                <Button
                  variant="secondary"
                  size="sm"
                  className="flex-1"
                  onClick={() => onPro(course._id)}
                >
                  <Highlighter className="w-4 h-4 ml-1" />
                  پرو
                </Button>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* کامپوننت Pagination */}
      {totalPages > 1 && onPageChange && (
        <div className="flex justify-center items-center gap-2 mt-8">
         <Button
            variant="outline"
            size="sm"
            onClick={() => onPageChange(currentPage + 1)}
            disabled={currentPage === totalPages}
          >
            بعدی
            <ChevronLeft className="w-4 h-4" />
          </Button>
          
          <div className="flex gap-1 flex-row-reverse">
            {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
              let pageNum;
              if (totalPages <= 5) {
                pageNum = i + 1;
              } else if (currentPage <= 3) {
                pageNum = i + 1;
              } else if (currentPage >= totalPages - 2) {
                pageNum = totalPages - 4 + i;
              } else {
                pageNum = currentPage - 2 + i;
              }
              
              return (
                <Button
                  key={pageNum}
                  variant={currentPage === pageNum ? "default" : "outline"}
                  size="sm"
                  onClick={() => onPageChange(pageNum)}
                  className="min-w-[40px]"
                >
                  {pageNum}
                </Button>
              );
            })}
          </div>
          <Button
            variant="outline"
            size="sm"
            onClick={() => onPageChange(currentPage - 1)}
            disabled={currentPage === 1}
          >
            <ChevronRight className="w-4 h-4" />
            قبلی
          </Button>
         
        </div>
      )}
    </div>
  );
}