'use client';

import React, { useState, useEffect } from 'react';
import Link from 'next/link';
import { apiRequest } from '@/lib/api';
import { useAuth } from '@/context/AuthContext';
import { toast } from '@/context/ToastContext';
import AuthModal from './AuthModal';
import RegistrationModal, { RegistrationModalSelectedItem } from './RegistrationModal';
import {
  Layers,
  Sparkles,
  ArrowRight,
  BookOpen,
  Clock,
  Video,
} from 'lucide-react';

export interface LessonItem {
  _id: string;
  title: string;
  slug: string;
  level?: string;
  course?: {
    _id: string;
    title: string;
  } | string;
  videoReference?: string;
  durationMinutes?: number;
  regularPrice: number;
  offerPrice?: number;
  isPublished?: boolean;
}

export interface CourseItem {
  _id: string;
  title: string;
  slug: string;
  level?: string;
  courseType: 'full_level' | 'sub_course' | 'individual_lesson';
  parentCourse?: {
    _id: string;
    title: string;
    level?: string;
    slug?: string;
  } | string;
  regularPrice: number;
  offerPrice?: number;
  isPublished?: boolean;
  thumbnailUrl?: string;
  chapters?: any[];
  validityMonths?: number;
}

export default function CourseHierarchyCatalog() {
  const { user } = useAuth();
  const [courses, setCourses] = useState<CourseItem[]>([]);
  const [lessons, setLessons] = useState<LessonItem[]>([]);
  const [loading, setLoading] = useState(true);

  // Registration & Auth Modal state
  const [isRegistrationOpen, setIsRegistrationOpen] = useState(false);
  const [authModalOpen, setAuthModalOpen] = useState(false);
  const [selectedItemForReg, setSelectedItemForReg] = useState<RegistrationModalSelectedItem | null>(null);

  const [userSubscriptions, setUserSubscriptions] = useState<any[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      const promises: Promise<any>[] = [
        apiRequest('/courses'),
        apiRequest('/lessons'),
      ];

      if (user && user.role !== 'admin' && user.role !== 'super_admin') {
        promises.push(apiRequest('/subscriptions'));
      }

      const [coursesRes, lessonsRes, subRes] = await Promise.all(promises);

      if (coursesRes.success && coursesRes.courses) {
        setCourses(coursesRes.courses);
      }
      if (lessonsRes.success && lessonsRes.lessons) {
        setLessons(lessonsRes.lessons);
      }
      if (subRes && subRes.success && Array.isArray(subRes.subscriptions)) {
        setUserSubscriptions(subRes.subscriptions);
      }
      setLoading(false);
    };

    fetchData();
  }, [user]);

  const isCoursePurchased = (courseId: string) => {
    if (!user || userSubscriptions.length === 0) return false;

    return userSubscriptions.some((sub: any) => {
      if (sub.status !== 'active') return false;
      if (sub.expiresAt && new Date(sub.expiresAt) < new Date()) return false;
      const subCourseId = typeof sub.course === 'object' ? sub.course?._id : sub.course;
      return subCourseId === courseId;
    });
  };

  const handleEnroll = (item: RegistrationModalSelectedItem) => {
    if (!user || user.role === 'admin' || user.role === 'super_admin') {
      toast.error('Student login is required to enroll in a course.');
      setAuthModalOpen(true);
      return;
    }
    setSelectedItemForReg(item);
    setIsRegistrationOpen(true);
  };

  // Build options for all courses for the dropdown in registration modal
  const courseOptions = courses.map((c) => {
    const price = c.offerPrice ?? c.regularPrice;
    return {
      label: `${c.title}${price ? ` - ${price} €` : ''}`,
      value: c._id,
      price,
    };
  });

  // Group Main Categories (`full_level` courses or distinct levels like A1, A2, B1, B2)
  const mainCategories = courses.filter(
    (c) => c.courseType === 'full_level' || (!c.parentCourse && c.courseType !== 'sub_course')
  );

  const renderPriceTag = (offerPrice?: number, regularPrice?: number) => {
    const finalPrice = offerPrice !== undefined && offerPrice !== null ? offerPrice : regularPrice;
    if (finalPrice === undefined || finalPrice === null || isNaN(Number(finalPrice))) {
      return null;
    }
    return `€${finalPrice}`;
  };

  return (
    <section id="courses" className="w-full bg-linear-to-b from-[#FFFDF5] via-[#FFF9E6] to-[#FAF5E4] py-16 sm:py-24 border-y border-amber-200/60 relative overflow-hidden">
      {/* Ambient Decorative Light Glows */}
      <div className="absolute -top-24 left-1/2 -translate-x-1/2 w-full max-w-7xl h-96 bg-[#FECE00]/15 rounded-full blur-3xl pointer-events-none" />
      <div className="absolute bottom-0 right-10 w-96 h-96 bg-amber-400/10 rounded-full blur-3xl pointer-events-none" />

      <div className="w-full max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
        {/* Section Header */}
        <div className="mb-8 text-center md:text-left flex flex-col md:flex-row md:items-end justify-between gap-6">
          <div>
            <div className="inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-[#FECE00] text-black border border-amber-400/50 text-xs font-black uppercase tracking-wider mb-3 shadow-xs">
              <Sparkles className="w-4 h-4 text-black" />
              <span>Structured Learning Curriculum</span>
            </div>
            <h2 className="font-courgette text-3xl sm:text-4xl md:text-5xl text-gray-900 font-normal tracking-tight">
              Course Catalog & Hierarchy
            </h2>
            <p className="text-sm sm:text-base text-gray-700 font-medium mt-3 max-w-2xl leading-relaxed">
              Select any main course level to view its full hierarchy, modules, and video lessons on its dedicated details page.
            </p>
          </div>
        </div>

        {loading ? (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 sm:gap-8">
            {[1, 2, 3].map((n) => (
              <div
                key={n}
                className="bg-white/90 rounded-3xl border border-amber-200/70 shadow-xs overflow-hidden animate-pulse flex flex-col justify-between"
              >
                {/* Header Skeleton */}
                <div className="bg-amber-500/10 p-5 border-b border-amber-100/70 flex items-center justify-between">
                  <div className="h-6 w-28 bg-amber-300/40 rounded-full" />
                  <div className="h-7 w-16 bg-amber-300/50 rounded-lg" />
                </div>

                {/* Body Skeleton */}
                <div className="p-6 space-y-4">
                  <div className="h-7 w-3/4 bg-gray-200/80 rounded-lg" />
                  <div className="space-y-2">
                    <div className="h-4 w-full bg-gray-100 rounded-md" />
                    <div className="h-4 w-4/5 bg-gray-100 rounded-md" />
                  </div>

                  <div className="grid grid-cols-2 gap-2 pt-2">
                    <div className="h-10 bg-amber-50/80 rounded-xl border border-amber-100/70" />
                    <div className="h-10 bg-amber-50/80 rounded-xl border border-amber-100/70" />
                  </div>
                </div>

                {/* Footer Skeleton */}
                <div className="p-5 bg-gray-50/80 border-t border-amber-100/80">
                  <div className="h-11 w-full bg-[#FECE00]/50 rounded-xl" />
                </div>
              </div>
            ))}
          </div>
        ) : mainCategories.length === 0 ? (
          <div className="bg-white/90 backdrop-blur-md rounded-3xl border border-amber-200/80 p-16 text-center text-sm font-semibold text-gray-600 shadow-md">
            No published course categories available at the moment.
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 sm:gap-8">
            {mainCategories.map((category) => {
              // Find Sub-Courses linked to this Main Category
              const subCourses = courses.filter((c) => {
                if (c.courseType !== 'sub_course') return false;
                const parentId = typeof c.parentCourse === 'object' ? c.parentCourse?._id : c.parentCourse;
                return parentId === category._id;
              });

              // Find Direct Lessons linked to this Main Category
              const directLessons = lessons.filter((l) => {
                const courseId = typeof l.course === 'object' ? l.course?._id : l.course;
                return courseId === category._id;
              });

              // Calculate discount savings if offer price exists
              const hasDiscount = category.offerPrice !== undefined && category.offerPrice !== null && category.regularPrice && category.regularPrice > category.offerPrice;
              const discountPercent = hasDiscount ? Math.round(((category.regularPrice - category.offerPrice!) / category.regularPrice) * 100) : 0;

              return (
                <div
                  key={category._id}
                  className="bg-white rounded-3xl border border-amber-200/90 shadow-xs hover:shadow-2xl transition-all duration-300 flex flex-col justify-between overflow-hidden group relative transform hover:-translate-y-1"
                >
                  {/* Top Gradient Banner / Price */}
                  <div className="bg-gradient-to-r from-amber-500/10 via-[#FECE00]/20 to-amber-100 p-5 border-b border-amber-100/70 relative">
                    <div className="flex items-center justify-between gap-2">
                      <span className="px-3.5 py-1 rounded-full bg-black text-[#FECE00] text-xs font-black uppercase tracking-wider shadow-xs flex items-center gap-1.5">
                        <Sparkles className="w-3.5 h-3.5" />
                        Full Course
                      </span>

                      {/* Right Price Badge */}
                      <div className="text-right">
                        {renderPriceTag(category.offerPrice, category.regularPrice) && (
                          <span className="text-2xl font-black text-gray-900 leading-none block">
                            {renderPriceTag(category.offerPrice, category.regularPrice)}
                          </span>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* Body Content */}
                  <div className="p-6 space-y-4 flex-1 flex flex-col justify-between">
                    <Link
                      href={`/courses/${category._id}`}
                      className="block space-y-2 group/title"
                    >
                      <h3 className="text-xl sm:text-2xl font-extrabold text-gray-900 tracking-tight group-hover/title:text-amber-600 transition-colors line-clamp-2 leading-snug">
                        {category.title}
                      </h3>
                      <p className="text-xs text-gray-600 font-medium line-clamp-2 leading-relaxed">
                        Master German language skills with structured sub-modules and interactive video lessons.
                      </p>
                    </Link>

                    {/* Meta Stats Badges */}
                    <div className="grid grid-cols-2 gap-2 pt-2">
                      <div className="p-2.5 bg-amber-50/70 rounded-xl border border-amber-100/80 flex items-center gap-2">
                        <Layers className="w-4 h-4 text-amber-700 shrink-0" />
                        <span className="text-xs font-bold text-gray-800">
                          {subCourses.length > 0
                            ? `${subCourses.length} Sub-Module${subCourses.length > 1 ? 's' : ''}`
                            : `${directLessons.length} Video Lesson${directLessons.length > 1 ? 's' : ''}`}
                        </span>
                      </div>

                      <div className="p-2.5 bg-amber-50/70 rounded-xl border border-amber-100/80 flex items-center gap-2">
                        <Clock className="w-4 h-4 text-amber-700 shrink-0" />
                        <span className="text-xs font-bold text-gray-800">
                          {category.validityMonths ? `${category.validityMonths} Months` : 'Lifetime Access'}
                        </span>
                      </div>
                    </div>
                  </div>

                  {/* Card Footer Actions */}
                  <div className="p-5 bg-gray-50/80 border-t border-amber-100/80 flex items-center gap-3">
                    <Link
                      href={`/courses/${category._id}`}
                      className="flex-1 py-3.5 px-4 rounded-xl bg-[#FECE00] hover:bg-black text-black hover:text-[#FECE00] font-extrabold text-sm uppercase tracking-wider shadow-md hover:shadow-lg transition-all flex items-center justify-center gap-2 active:scale-95 group/btn"
                    >
                      <span>View Details</span>
                      <ArrowRight className="w-4 h-4 text-black group-hover/btn:text-[#FECE00] group-hover/btn:translate-x-1 transition-all" />
                    </Link>

                    {/* {isCoursePurchased(category._id) ? (
                      <Link
                        href="/student/dashboard"
                        className="flex-1 py-3 px-4 rounded-xl bg-emerald-50 border border-emerald-300 text-emerald-800 font-extrabold text-xs shadow-2xs hover:bg-emerald-100 transition-all flex items-center justify-center gap-1"
                      >
                        <span>Purchased</span>
                      </Link>
                    ) : (
                      <button
                        type="button"
                        onClick={() => {
                          handleEnroll({
                            id: category._id,
                            title: category.title,
                            price: category.offerPrice ?? category.regularPrice,
                            type: 'course',
                            level: category.level,
                          });
                        }}
                        className="flex-1 py-3 px-4 rounded-xl bg-[#FECE00] hover:bg-black text-black hover:text-[#FECE00] font-black text-xs uppercase tracking-wider shadow-xs hover:shadow-lg transition-all flex items-center justify-center gap-1 transform active:scale-95 cursor-pointer"
                      >
                        <span>Enroll Now</span>
                      </button>
                    )} */}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Registration Modal Popup */}
      <RegistrationModal
        isOpen={isRegistrationOpen}
        onClose={() => setIsRegistrationOpen(false)}
        selectedItem={selectedItemForReg}
        coursesOptions={courseOptions}
      />

      {/* Auth Modal Popup for student login requirement */}
      <AuthModal
        isOpen={authModalOpen}
        onClose={() => setAuthModalOpen(false)}
        initialMode="login"
      />
    </section>
  );
}
