'use client';

import React, { useState, useEffect } from 'react';
import { apiRequest, uploadFile } from '@/lib/api';
import { uploadDirectToS3 } from '@/lib/s3Upload';
import SecureVideoPlayer from '@/components/SecureVideoPlayer';
import { extractFilename, getMediaUrl } from '@/lib/media';
import { X, Video, Upload, FileText, CheckCircle, Loader2 } from 'lucide-react';
import { toast } from '@/context/ToastContext';
import { CourseItem } from './CreateCourseModal';

export interface LessonItem {
  _id: string;
  course: string | any;
  chapterNumber: number;
  title: string;
  description?: string;
  videoReference: string;
  durationMinutes?: number;
  price?: number;
  isDownloadableScriptActive: boolean;
  scriptFileUrl?: string;
  isDownloadableHomeworkActive: boolean;
  homeworkFileUrl?: string;
  order: number;
}

interface CreateLessonModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  editingLesson?: LessonItem | null;
  courses: CourseItem[];
  preselectedCourseId?: string;
}

export default function CreateLessonModal({
  isOpen,
  onClose,
  onSuccess,
  editingLesson = null,
  courses,
  preselectedCourseId = '',
}: CreateLessonModalProps) {
  const [parentCourseId, setParentCourseId] = useState<string>('');
  const [subCourseId, setSubCourseId] = useState<string>('');
  const [lessonTitle, setLessonTitle] = useState('');
  const [lessonVideoRef, setLessonVideoRef] = useState('');
  const [durationMins, setDurationMins] = useState<number>(15);
  const [durationSecs, setDurationSecs] = useState<number>(0);
  const [lessonPrice, setLessonPrice] = useState<number>(0);
  const [lessonChapterNum, setLessonChapterNum] = useState<number>(1);
  const [scriptUrl, setScriptUrl] = useState('');
  const [homeworkUrl, setHomeworkUrl] = useState('');
  const [submitting, setSubmitting] = useState(false);

  // Upload States
  const [uploadingVideo, setUploadingVideo] = useState(false);
  const [uploadProgress, setUploadProgress] = useState<number>(0);
  const [uploadingScript, setUploadingScript] = useState(false);
  const [uploadingHomework, setUploadingHomework] = useState(false);
  const [videoInputMode, setVideoInputMode] = useState<'upload' | 'url'>('upload');

  // Filter major courses and sub-courses
  const majorCourses = courses.filter((c) => !c.parentCourse || c.courseType === 'full_level');
  const getSubCourses = (majorId: string) => courses.filter((c) => {
    const pId = typeof c.parentCourse === 'object' ? (c.parentCourse as any)?._id : c.parentCourse;
    return String(pId) === String(majorId);
  });
  const currentSubCourses = parentCourseId ? getSubCourses(parentCourseId) : [];

  useEffect(() => {
    if (editingLesson) {
      const courseObj = typeof editingLesson.course === 'object' ? (editingLesson.course as any) : null;
      const targetId = courseObj ? courseObj._id : String(editingLesson.course);
      const foundCourse = courses.find((c) => c._id === targetId);

      if (foundCourse && foundCourse.parentCourse) {
        const pId = typeof foundCourse.parentCourse === 'object' ? (foundCourse.parentCourse as any)._id : String(foundCourse.parentCourse);
        setParentCourseId(pId);
        setSubCourseId(foundCourse._id);
      } else {
        setParentCourseId(targetId || '');
        setSubCourseId('');
      }

      setLessonTitle(editingLesson.title);
      setLessonVideoRef(editingLesson.videoReference);

      const totalDur = editingLesson.durationMinutes || 15;
      const mins = Math.floor(totalDur);
      const secs = Math.round((totalDur - mins) * 60);
      setDurationMins(mins);
      setDurationSecs(secs);

      setLessonPrice(editingLesson.price || 0);
      setLessonChapterNum(editingLesson.chapterNumber || 1);
      setScriptUrl(editingLesson.scriptFileUrl || '');
      setHomeworkUrl(editingLesson.homeworkFileUrl || '');
    } else {
      if (preselectedCourseId) {
        const found = courses.find((c) => c._id === preselectedCourseId);
        if (found && found.parentCourse) {
          const pId = typeof found.parentCourse === 'object' ? (found.parentCourse as any)._id : String(found.parentCourse);
          setParentCourseId(pId);
          setSubCourseId(found._id);
        } else {
          setParentCourseId(preselectedCourseId);
          setSubCourseId('');
        }
      } else {
        setParentCourseId(majorCourses[0]?._id || '');
        setSubCourseId('');
      }
      setLessonTitle('');
      setLessonVideoRef('');
      setDurationMins(15);
      setDurationSecs(0);
      setLessonPrice(0);
      setLessonChapterNum(1);
      setScriptUrl('');
      setHomeworkUrl('');
    }
  }, [editingLesson, isOpen, preselectedCourseId, courses]);

  if (!isOpen) return null;

  // File Upload Handlers (Direct S3 Upload)
  const handleVideoFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploadingVideo(true);
    setUploadProgress(0);

    const res = await uploadDirectToS3(file, 'lessons-videos', (percent) => {
      setUploadProgress(percent);
    });

    setUploadingVideo(false);

    if (res.success && res.fileKey) {
      setLessonVideoRef(res.fileKey);
      toast.success('Video uploaded directly to AWS S3 bucket successfully!');
    } else {
      toast.error(res.error || 'Direct AWS S3 video upload failed');
    }
  };

  const handleScriptFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploadingScript(true);
    const res = await uploadFile(file, 'script');
    setUploadingScript(false);

    if (res.success && (res.filename || res.url || res.relativeUrl)) {
      setScriptUrl(extractFilename(res.filename || res.url || res.relativeUrl));
      toast.success('Script PDF uploaded successfully!');
    } else {
      toast.error(res.error || 'Script PDF upload failed');
    }
  };

  const handleHomeworkFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploadingHomework(true);
    const res = await uploadFile(file, 'homework');
    setUploadingHomework(false);

    if (res.success && (res.filename || res.url || res.relativeUrl)) {
      setHomeworkUrl(extractFilename(res.filename || res.url || res.relativeUrl));
      toast.success('Homework PDF uploaded successfully!');
    } else {
      toast.error(res.error || 'Homework PDF upload failed');
    }
  };

  const handleSubmitLesson = async (e: React.FormEvent) => {
    e.preventDefault();
    const effectiveCourseId = subCourseId || parentCourseId;

    if (!lessonTitle.trim() || !lessonVideoRef.trim() || !effectiveCourseId) {
      toast.warning('Please provide a lesson title, video file or reference, and select a target course.');
      return;
    }

    setSubmitting(true);
    const calculatedDuration = Number((Number(durationMins) + Number(durationSecs) / 60).toFixed(2));

    const payload = {
      course: effectiveCourseId,
      title: lessonTitle,
      chapterNumber: Number(lessonChapterNum),
      videoReference: lessonVideoRef,
      durationMinutes: calculatedDuration,
      price: Number(lessonPrice),
      isDownloadableScriptActive: Boolean(scriptUrl),
      scriptFileUrl: scriptUrl,
      isDownloadableHomeworkActive: Boolean(homeworkUrl),
      homeworkFileUrl: homeworkUrl,
      order: Number(lessonChapterNum),
    };

    let res;
    if (editingLesson) {
      res = await apiRequest(`/lessons/${editingLesson._id}`, {
        method: 'PATCH',
        body: JSON.stringify(payload),
      });
    } else {
      res = await apiRequest('/lessons', {
        method: 'POST',
        body: JSON.stringify(payload),
      });
    }

    setSubmitting(false);

    if (res.success) {
      toast.success(editingLesson ? 'Lesson updated successfully!' : 'Lesson created successfully!');
      onSuccess();
      onClose();
    } else {
      toast.error(res.error || 'Failed to save lesson');
    }
  };

  return (
    <div className="fixed inset-0 z-[100] bg-black/50 backdrop-blur-xs flex items-center justify-center p-4 overflow-y-auto !m-0">
      <div className="bg-white max-w-3xl w-full rounded-2xl shadow-2xl border border-gray-200 overflow-hidden my-4">
        <div className="p-5 border-b border-gray-200 flex items-center justify-between bg-gray-50">
          <h2 className="text-xl font-extrabold text-gray-900 flex items-center gap-2">
            <Video className="w-5 h-5 text-amber-600" />
            <span>{editingLesson ? 'Edit Lesson' : 'Create Lesson'}</span>
          </h2>
          <button
            onClick={onClose}
            className="p-1.5 rounded-lg text-gray-400 hover:text-gray-700 hover:bg-gray-200 transition"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        <form onSubmit={handleSubmitLesson} className="p-6 space-y-4 max-h-[80vh] overflow-y-auto">
          {/* Row 1: Parent Course & Sub-Course Selection */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-bold uppercase text-gray-700 mb-1">
                Parent Course <span className="text-red-500">*</span>
              </label>
              <select
                required
                value={parentCourseId}
                onChange={(e) => {
                  setParentCourseId(e.target.value);
                  setSubCourseId('');
                }}
                className="w-full px-3.5 py-2.5 rounded-xl border border-gray-300 text-sm font-semibold focus:border-[#FECE00] outline-none bg-white text-gray-900"
              >
                <option value="">-- Select Parent Course --</option>
                {majorCourses.map((c) => (
                  <option key={c._id} value={c._id}>
                    {c.level ? `${c.level} - ` : ''}{c.title}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-xs font-bold uppercase text-gray-700 mb-1">
                Sub-Course (Optional)
              </label>
              <select
                value={subCourseId}
                disabled={!parentCourseId || currentSubCourses.length === 0}
                onChange={(e) => setSubCourseId(e.target.value)}
                className="w-full px-3.5 py-2.5 rounded-xl border border-gray-300 text-sm font-semibold focus:border-[#FECE00] outline-none bg-white text-gray-900 disabled:bg-gray-100 disabled:text-gray-400 cursor-pointer disabled:cursor-not-allowed"
              >
                {!parentCourseId ? (
                  <option value="">Select Parent Course First</option>
                ) : currentSubCourses.length === 0 ? (
                  <option value="">No Sub-courses (Direct Major Course)</option>
                ) : (
                  <>
                    <option value="">-- Direct Parent Course (No Sub-course) --</option>
                    {currentSubCourses.map((sub) => (
                      <option key={sub._id} value={sub._id}>
                        {sub.title}
                      </option>
                    ))}
                  </>
                )}
              </select>
            </div>
          </div>

          {/* Row 2: Lesson Title */}
          <div>
            <label className="block text-xs font-bold uppercase text-gray-700 mb-1">
              Lesson Title <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              required
              value={lessonTitle}
              onChange={(e) => setLessonTitle(e.target.value)}
              placeholder="e.g. Lesson 1: German Alphabet & Pronunciation"
              className="w-full px-3.5 py-2.5 rounded-xl border border-gray-300 text-sm font-semibold focus:border-[#FECE00] outline-none"
            />
          </div>

          {/* Lesson Video Upload Section */}
          <div className="space-y-2">
            <div className="flex items-center justify-between">
              <label className="block text-xs font-bold uppercase text-gray-700">
                Lesson Video File <span className="text-red-500">*</span>
              </label>
              <div className="flex items-center gap-2 text-[11px]">
                <button
                  type="button"
                  onClick={() => setVideoInputMode('upload')}
                  className={`px-2 py-0.5 rounded-md font-bold ${videoInputMode === 'upload' ? 'bg-[#FECE00] text-black' : 'text-gray-500 hover:bg-gray-100'}`}
                >
                  Upload File
                </button>
                {/* <button
                  type="button"
                  onClick={() => setVideoInputMode('url')}
                  className={`px-2 py-0.5 rounded-md font-bold ${videoInputMode === 'url' ? 'bg-[#FECE00] text-black' : 'text-gray-500 hover:bg-gray-100'}`}
                >
                  URL / Stream ID
                </button> */}
              </div>
            </div>

            {videoInputMode === 'upload' ? (
              <div className="p-3.5 rounded-xl border-2 border-dashed border-gray-300 bg-gray-50/70 transition space-y-3">
                <input
                  type="file"
                  accept="video/*"
                  onChange={handleVideoFileUpload}
                  id="video-file-upload"
                  className="hidden"
                />

                {uploadingVideo ? (
                  <div className="py-6 flex flex-col items-center justify-center gap-2 text-amber-700 font-bold text-xs">
                    <div className="flex items-center gap-2">
                      <Loader2 className="w-5 h-5 animate-spin text-amber-600" />
                      <span>Uploading directly to AWS S3 ({uploadProgress}%)...</span>
                    </div>
                    <div className="w-full max-w-xs bg-gray-200 rounded-full h-2 overflow-hidden">
                      <div
                        className="bg-[#FECE00] h-2 rounded-full transition-all duration-300"
                        style={{ width: `${uploadProgress}%` }}
                      />
                    </div>
                  </div>
                ) : lessonVideoRef ? (
                  <div className="space-y-2">
                    <SecureVideoPlayer
                      fileKey={lessonVideoRef}
                      courseId={parentCourseId || ''}
                      title={lessonTitle || 'Lesson Video Preview'}
                    />
                    <div className="flex items-center justify-between text-xs px-1">
                      <span className="flex items-center gap-1.5 text-emerald-700 font-bold">
                        <CheckCircle className="w-4 h-4 text-emerald-600 shrink-0" />
                        <span>Uploaded to S3: {lessonVideoRef}</span>
                      </span>
                      <label
                        htmlFor="video-file-upload"
                        className="cursor-pointer text-xs font-extrabold text-amber-800 hover:underline bg-amber-50 px-2.5 py-1 rounded-lg border border-amber-200"
                      >
                        Change Video File
                      </label>
                    </div>
                  </div>
                ) : (
                  <label
                    htmlFor="video-file-upload"
                    className="cursor-pointer py-6 flex flex-col items-center justify-center gap-1.5"
                  >
                    <Upload className="w-6 h-6 text-amber-600" />
                    <span className="text-xs font-bold text-gray-800">
                      Click to select & upload MP4 / Video file directly to AWS S3
                    </span>
                    <span className="text-[11px] text-gray-500 font-medium">
                      Uploaded directly to AWS S3 Bucket: <strong className="text-amber-700">apkagermanschool</strong>
                    </span>
                  </label>
                )}
              </div>
            ) : (
              <div className="space-y-2">
                <input
                  type="text"
                  required
                  value={lessonVideoRef}
                  onChange={(e) => setLessonVideoRef(e.target.value)}
                  placeholder="CDN Stream ID or Video Reference URL"
                  className="w-full px-3.5 py-2.5 rounded-xl border border-gray-300 text-xs font-semibold focus:border-[#FECE00] outline-none"
                />
                {lessonVideoRef && (
                  <video
                    controls
                    src={getMediaUrl(lessonVideoRef, 'videos')}
                    className="w-full max-h-52 rounded-xl bg-black object-contain shadow-sm border border-gray-200"
                  />
                )}
              </div>
            )}
          </div>

          {/* Row 3: Duration (Minutes & Seconds) & Price */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-xs font-bold uppercase text-gray-700 mb-1">
                Lesson Price (€)
              </label>
              <input
                type="number"
                min="0"
                value={lessonPrice}
                onChange={(e) => setLessonPrice(Number(e.target.value))}
                placeholder="0 (Free or included in course)"
                className="w-full px-3.5 py-2.5 rounded-xl border border-gray-300 text-sm font-semibold focus:border-[#FECE00] outline-none"
              />
            </div>

            <div>
              <label className="block text-xs font-bold uppercase text-gray-700 mb-1">
                Duration (Minutes & Seconds)
              </label>
              <div className="grid grid-cols-2 gap-3">
                <div className="relative flex items-center">
                  <input
                    type="number"
                    min="0"
                    value={durationMins}
                    onChange={(e) => setDurationMins(Math.max(0, Number(e.target.value)))}
                    placeholder="0"
                    className="w-full px-3.5 py-2.5 rounded-xl border border-gray-300 text-sm font-semibold focus:border-[#FECE00] outline-none pr-10"
                  />
                  <span className="absolute right-3.5 text-xs font-extrabold text-gray-400 pointer-events-none">mins</span>
                </div>
                <div className="relative flex items-center">
                  <input
                    type="number"
                    min="0"
                    max="59"
                    value={durationSecs}
                    onChange={(e) => setDurationSecs(Math.min(59, Math.max(0, Number(e.target.value))))}
                    placeholder="0"
                    className="w-full px-3.5 py-2.5 rounded-xl border border-gray-300 text-sm font-semibold focus:border-[#FECE00] outline-none pr-10"
                  />
                  <span className="absolute right-3.5 text-xs font-extrabold text-gray-400 pointer-events-none">secs</span>
                </div>
              </div>
            </div>
          </div>

          {/* Row 4: Script & Homework PDF Uploads */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Script PDF File Upload */}
            <div className="space-y-1.5 min-w-0">
              <label className="block text-xs font-bold uppercase text-gray-700">
                Script PDF File (Optional)
              </label>
              <div className="flex items-center gap-2">
                <label className="flex-1 min-w-0 cursor-pointer">
                  <input
                    type="file"
                    accept=".pdf,application/pdf"
                    onChange={handleScriptFileUpload}
                    className="hidden"
                  />
                  <div className="px-3 py-2 rounded-xl border border-gray-300 bg-gray-50 hover:bg-gray-100 transition text-xs font-semibold text-gray-700 flex items-center justify-between gap-1.5 min-w-0">
                    {uploadingScript ? (
                      <span className="flex items-center gap-1.5 text-amber-700 font-bold truncate min-w-0">
                        <Loader2 className="w-4 h-4 animate-spin shrink-0" />
                        <span className="truncate">Uploading...</span>
                      </span>
                    ) : scriptUrl ? (
                      <span className="flex items-center gap-1.5 text-red-700 font-extrabold truncate min-w-0">
                        <FileText className="w-4 h-4 text-red-600 shrink-0" />
                        <span className="truncate text-[11px]">Script PDF</span>
                      </span>
                    ) : (
                      <span className="flex items-center gap-1.5 text-gray-500 truncate min-w-0">
                        <FileText className="w-4 h-4 text-amber-600 shrink-0" />
                        <span className="truncate">Upload Script PDF</span>
                      </span>
                    )}
                    <span className="px-2 py-0.5 rounded-md bg-white border border-gray-300 text-[11px] font-bold text-gray-800 shadow-2xs shrink-0">
                      {scriptUrl ? 'Change' : 'Browse'}
                    </span>
                  </div>
                </label>
                {scriptUrl && (
                  <button
                    type="button"
                    onClick={() => setScriptUrl('')}
                    className="p-1.5 rounded-xl text-red-600 hover:bg-red-50 border border-red-200 transition shrink-0"
                    title="Remove Script PDF"
                  >
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>
            </div>

            {/* Homework PDF File Upload */}
            <div className="space-y-1.5 min-w-0">
              <label className="block text-xs font-bold uppercase text-gray-700">
                Homework PDF File (Optional)
              </label>
              <div className="flex items-center gap-2">
                <label className="flex-1 min-w-0 cursor-pointer">
                  <input
                    type="file"
                    accept=".pdf,application/pdf"
                    onChange={handleHomeworkFileUpload}
                    className="hidden"
                  />
                  <div className="px-3 py-2 rounded-xl border border-gray-300 bg-gray-50 hover:bg-gray-100 transition text-xs font-semibold text-gray-700 flex items-center justify-between gap-1.5 min-w-0">
                    {uploadingHomework ? (
                      <span className="flex items-center gap-1.5 text-amber-700 font-bold truncate min-w-0">
                        <Loader2 className="w-4 h-4 animate-spin shrink-0" />
                        <span className="truncate">Uploading...</span>
                      </span>
                    ) : homeworkUrl ? (
                      <span className="flex items-center gap-1.5 text-indigo-700 font-extrabold truncate min-w-0">
                        <FileText className="w-4 h-4 text-indigo-600 shrink-0" />
                        <span className="truncate text-[11px]">Homework PDF</span>
                      </span>
                    ) : (
                      <span className="flex items-center gap-1.5 text-gray-500 truncate min-w-0">
                        <FileText className="w-4 h-4 text-indigo-600 shrink-0" />
                        <span className="truncate">Upload Homework PDF</span>
                      </span>
                    )}
                    <span className="px-2 py-0.5 rounded-md bg-white border border-gray-300 text-[11px] font-bold text-gray-800 shadow-2xs shrink-0">
                      {homeworkUrl ? 'Change' : 'Browse'}
                    </span>
                  </div>
                </label>
                {homeworkUrl && (
                  <button
                    type="button"
                    onClick={() => setHomeworkUrl('')}
                    className="p-1.5 rounded-xl text-red-600 hover:bg-red-50 border border-red-200 transition shrink-0"
                    title="Remove Homework PDF"
                  >
                    <X className="w-4 h-4" />
                  </button>
                )}
              </div>
            </div>
          </div>

          <div className="flex items-center justify-end gap-3 pt-3 border-t border-gray-200">
            <button
              type="button"
              onClick={onClose}
              disabled={submitting || uploadingVideo || uploadingScript || uploadingHomework}
              className="px-5 py-2.5 rounded-xl text-xs font-extrabold text-gray-700 bg-gray-100 hover:bg-gray-200 transition cursor-pointer disabled:opacity-50"
            >
              Cancel
            </button>
            <button
              type="submit"
              disabled={submitting || uploadingVideo || uploadingScript || uploadingHomework}
              className="px-5 py-2.5 rounded-xl bg-[#FECE00] hover:bg-[#e5b800] text-black font-extrabold text-xs shadow-xs transition-all active:scale-95 flex items-center justify-center gap-2 cursor-pointer border border-amber-300 disabled:opacity-50"
            >
              {submitting ? 'Saving...' : editingLesson ? 'Save Lesson' : 'Create Lesson'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
