'use client';

import React, { useState, useEffect } from 'react';
import { apiRequest } from '@/lib/api';
import { getMediaUrl } from '@/lib/media';
import { Video, Edit3, Trash2, FileText, Clock, Filter, FilePlus, CheckCircle, XCircle } from 'lucide-react';
import CreateLessonModal, { LessonItem } from '@/components/admin/CreateLessonModal';
import ConfirmDeleteModal from '@/components/admin/ConfirmDeleteModal';
import { CourseItem } from '@/components/admin/CreateCourseModal';
import { toast } from '@/context/ToastContext';

export default function AdminLessonsPage() {
  const [lessons, setLessons] = useState<LessonItem[]>([]);
  const [courses, setCourses] = useState<CourseItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedCourseFilter, setSelectedCourseFilter] = useState<string>('all');
  const [selectedLevelFilter, setSelectedLevelFilter] = useState<string>('all');

  // Modal states
  const [showLessonModal, setShowLessonModal] = useState(false);
  const [editingLesson, setEditingLesson] = useState<LessonItem | null>(null);

  // Delete Confirmation state
  const [deletingLesson, setDeletingLesson] = useState<LessonItem | null>(null);
  const [deleting, setDeleting] = useState(false);

  const fetchData = async () => {
    setLoading(true);
    const params = new URLSearchParams();
    if (selectedCourseFilter !== 'all') {
      params.append('courseId', selectedCourseFilter);
    }
    const queryString = params.toString() ? `?${params.toString()}` : '';

    const [lessonsRes, coursesRes] = await Promise.all([
      apiRequest(`/lessons${queryString}`),
      apiRequest('/courses'),
    ]);

    if (lessonsRes.success && lessonsRes.lessons) {
      setLessons(lessonsRes.lessons);
    }
    if (coursesRes.success && coursesRes.courses) {
      setCourses(coursesRes.courses);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchData();
  }, [selectedCourseFilter]);

  const openCreateLessonModal = () => {
    setEditingLesson(null);
    setShowLessonModal(true);
  };

  const openEditLessonModal = (lesson: LessonItem) => {
    setEditingLesson(lesson);
    setShowLessonModal(true);
  };

  const handleConfirmDeleteLesson = async () => {
    if (!deletingLesson) return;
    setDeleting(true);
    const res = await apiRequest(`/lessons/${deletingLesson._id}`, { method: 'DELETE' });
    setDeleting(false);

    if (res.success) {
      toast.success('Lesson deleted successfully');
      setDeletingLesson(null);
      fetchData();
    } else {
      toast.error(res.error || 'Failed to delete lesson');
    }
  };

  const getCourseDetails = (courseIdOrObj: string | any) => {
    const cId = typeof courseIdOrObj === 'object' ? courseIdOrObj?._id : courseIdOrObj;
    return courses.find((c) => String(c._id) === String(cId));
  };

  return (
    <div className="space-y-8 max-w-7xl mx-auto">
      {/* Page Header & Create Lesson Action */}
      <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-gray-900 tracking-tight flex items-center gap-3">
            <span>Lesson Management</span>
          </h1>
          {/* <p className="text-sm text-gray-500 mt-1">
            Create, view, attach, and configure downloadable scripts & homework files for individual lessons
          </p> */}
        </div>

        <button
          onClick={openCreateLessonModal}
          className="px-4 py-2 bg-[#FECE00] hover:bg-[#e5b800] text-black text-sm font-medium rounded-lg shadow-sm transition-colors flex items-center gap-2 cursor-pointer"
        >
          <FilePlus className="w-5 h-5 text-black" />
          <span>Create Lesson</span>
        </button>
      </div>

      {/* Filter Toolbar */}
      <div className="bg-white p-4 rounded-2xl border border-gray-200 shadow-xs flex flex-col sm:flex-row items-center justify-between gap-4">
        <div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-gray-600">
          <Filter className="w-4 h-4 text-amber-600" />
          <span>Filter Lessons:</span>
        </div>

        <div className="flex flex-wrap items-center gap-3 w-full sm:w-auto">
          {/* Level Filter */}
          {/* <select
            value={selectedLevelFilter}
            onChange={(e) => setSelectedLevelFilter(e.target.value)}
            className="px-3.5 py-2 rounded-xl border border-gray-300 text-xs font-bold text-gray-700 bg-white outline-none focus:border-[#FECE00]"
          >
            <option value="all">All Levels (A1 - B2)</option>
            <option value="A1">Level A1</option>
            <option value="A2">Level A2</option>
            <option value="B1">Level B1</option>
            <option value="B2">Level B2</option>
          </select> */}

          {/* Course Filter */}
          <select
            value={selectedCourseFilter}
            onChange={(e) => setSelectedCourseFilter(e.target.value)}
            className="px-3.5 py-2 rounded-xl border border-gray-300 text-xs font-bold text-gray-700 bg-white outline-none focus:border-[#FECE00]"
          >
            <option value="all">All Courses ({courses.length})</option>
            {courses.map((c) => (
              <option key={c._id} value={c._id}>
                {c.level} - {c.title}
              </option>
            ))}
          </select>
        </div>
      </div>

      {/* Lessons List Grid */}
      <div className="bg-white rounded-2xl border border-gray-200 shadow-xs overflow-hidden">
        <div className="p-6 border-b border-gray-200 bg-gray-50/50 flex items-center justify-between">
          <div className="flex items-center gap-2 text-sm font-bold text-gray-800">
            <Video className="w-4 h-4 text-blue-600" />
            <span>Lessons</span>
          </div>
          <span className="text-xs text-gray-500 font-medium">
            Showing {lessons.length} Lesson{lessons.length !== 1 ? 's' : ''}
          </span>
        </div>

        {loading ? (
          <div className="p-12 text-center text-gray-500 text-sm font-semibold">
            Loading lesson catalog...
          </div>
        ) : lessons.length === 0 ? (
          <div className="p-12 text-center text-gray-500 text-sm">
            {lessons.length === 0
              ? 'No lessons created yet. Click "Create Lesson" to add your first lesson!'
              : 'No lessons match the selected filters.'}
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5 p-6">
            {lessons.map((lesson) => {
              const course = getCourseDetails(lesson.course);
              return (
                <div
                  key={lesson._id}
                  className="p-5 rounded-2xl bg-white border border-gray-200 shadow-xs hover:shadow-md transition flex flex-col justify-between space-y-4"
                >
                  <div className="space-y-3">
                    {/* Header Level & Course Badge */}
                    <div className="flex items-center justify-between gap-2">
                      <span className="px-2.5 py-0.5 rounded-full bg-amber-100 text-amber-900 border border-amber-300 text-[11px] font-black">
                        {course?.level || 'German'}
                      </span>
                      <span className="text-[11px] font-bold text-gray-500 truncate max-w-[180px]">
                        {course?.title || 'Standalone'}
                      </span>
                    </div>

                    {/* Lesson Title */}
                    <h3 className="font-bold text-base text-gray-900 leading-snug line-clamp-2">
                      {lesson.title}
                    </h3>

                    {/* Video Preview & Details */}
                    <div className="space-y-2 pt-1">
                      {lesson.videoReference ? (
                        <div className="space-y-1">
                          <video
                            controls
                            src={getMediaUrl(lesson.videoReference, 'videos')}
                            className="w-full h-36 rounded-xl bg-black object-contain shadow-xs border border-gray-200"
                          />
                        </div>
                      ) : (
                        <div className="flex items-center gap-2 text-xs text-gray-400 italic">
                          <Video className="w-3.5 h-3.5 shrink-0" />
                          <span>No video file attached</span>
                        </div>
                      )}

                      <div className="flex items-center justify-between text-xs text-gray-600 pt-1">
                        <div className="flex items-center gap-1.5">
                          <Clock className="w-3.5 h-3.5 text-amber-600 shrink-0" />
                          <span className="font-semibold text-gray-700">
                            {lesson.durationMinutes || 0} Mins
                          </span>
                        </div>
                        {lesson.price ? (
                          <span className="font-extrabold text-emerald-700 bg-emerald-50 px-2 py-0.5 rounded-md border border-emerald-200">
                            €{lesson.price}
                          </span>
                        ) : (
                          <span className="font-bold text-gray-500 bg-gray-100 px-2 py-0.5 rounded-md">
                            Free
                          </span>
                        )}
                      </div>
                    </div>

                    {/* Script & Homework Badges */}
                    <div className="pt-2 border-t border-gray-100 space-y-1 text-[11px]">
                      <div className="flex items-center justify-between">
                        <span className="text-gray-500 flex items-center gap-1 font-medium">
                          <FileText className="w-3 h-3 text-amber-600" />
                          Script PDF:
                        </span>
                        {lesson.isDownloadableScriptActive ? (
                          <span className="text-emerald-700 font-bold flex items-center gap-1">
                            <CheckCircle className="w-3 h-3 text-emerald-600" /> Attached
                          </span>
                        ) : (
                          <span className="text-gray-400 font-medium flex items-center gap-1">
                            <XCircle className="w-3 h-3 text-gray-300" /> None
                          </span>
                        )}
                      </div>

                      <div className="flex items-center justify-between">
                        <span className="text-gray-500 flex items-center gap-1 font-medium">
                          <FileText className="w-3 h-3 text-indigo-600" />
                          Homework PDF:
                        </span>
                        {lesson.isDownloadableHomeworkActive ? (
                          <span className="text-emerald-700 font-bold flex items-center gap-1">
                            <CheckCircle className="w-3 h-3 text-emerald-600" /> Attached
                          </span>
                        ) : (
                          <span className="text-gray-400 font-medium flex items-center gap-1">
                            <XCircle className="w-3 h-3 text-gray-300" /> None
                          </span>
                        )}
                      </div>
                    </div>
                  </div>

                  {/* Actions Footer */}
                  <div className="flex items-center justify-end gap-2 pt-3 border-t border-gray-100">
                    <button
                      onClick={() => openEditLessonModal(lesson)}
                      className="px-3 py-1.5 rounded-xl text-gray-700 hover:text-black hover:bg-gray-100 border border-gray-200 text-xs font-bold transition flex items-center gap-1.5"
                    >
                      <Edit3 className="w-3.5 h-3.5" />
                      <span>Edit</span>
                    </button>
                    <button
                      onClick={() => setDeletingLesson(lesson)}
                      className="px-3 py-1.5 rounded-xl text-red-600 hover:bg-red-50 border border-red-200 text-xs font-bold transition flex items-center gap-1.5"
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                      <span>Delete</span>
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Dedicated Standalone Lesson Modal */}
      <CreateLessonModal
        isOpen={showLessonModal}
        onClose={() => setShowLessonModal(false)}
        onSuccess={fetchData}
        editingLesson={editingLesson}
        courses={courses}
      />

      {/* Confirm Delete Modal */}
      <ConfirmDeleteModal
        isOpen={Boolean(deletingLesson)}
        onClose={() => setDeletingLesson(null)}
        onConfirm={handleConfirmDeleteLesson}
        loading={deleting}
        title="Delete Lesson"
        description={`Are you sure you want to delete "${deletingLesson?.title}"? This action cannot be undone and will permanently remove this lesson.`}
      />
    </div>
  );
}
