'use client';

import React, { useState, useEffect } from 'react';
import { apiRequest } from '@/lib/api';
import { X, FolderPlus } from 'lucide-react';
import { toast } from '@/context/ToastContext';

export interface CourseItem {
  _id: string;
  level?: string;
  courseType: 'full_level' | 'sub_course' | 'individual_lesson';
  title: string;
  slug: string;
  description?: string;
  parentCourse?: string | null;
  regularPrice: number;
  offerPrice?: number;
  currency: string;
  isPublished: boolean;
  validityMonths: number;
  chapters?: any[];
}

interface CreateCourseModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  editingCourse?: CourseItem | null;
  allCourses: CourseItem[];
}

export default function CreateCourseModal({
  isOpen,
  onClose,
  onSuccess,
  editingCourse = null,
  allCourses,
}: CreateCourseModalProps) {
  const [courseTitle, setCourseTitle] = useState('');
  const [courseLevel, setCourseLevel] = useState<string>('General');
  const [parentCourseId, setParentCourseId] = useState<string>(''); // empty string = Major Course
  const [courseDescription, setCourseDescription] = useState('');
  const [regularPrice, setRegularPrice] = useState<number>(99);
  const [offerPrice, setOfferPrice] = useState<number | undefined>(79);
  const [validityMonths, setValidityMonths] = useState<number>(4);
  const [isPublished, setIsPublished] = useState<boolean>(true);
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    if (editingCourse) {
      setCourseTitle(editingCourse.title);
      setCourseLevel(editingCourse.level || 'General');
      setParentCourseId(editingCourse.parentCourse ? String(editingCourse.parentCourse) : '');
      setCourseDescription(editingCourse.description || '');
      setRegularPrice(editingCourse.regularPrice);
      setOfferPrice(editingCourse.offerPrice);
      setValidityMonths(editingCourse.validityMonths || 4);
      setIsPublished(editingCourse.isPublished);
    } else {
      setCourseTitle('');
      setCourseLevel('General');
      setParentCourseId('');
      setCourseDescription('');
      setRegularPrice(99);
      setOfferPrice(79);
      setValidityMonths(4);
      setIsPublished(true);
    }
  }, [editingCourse, isOpen]);

  if (!isOpen) return null;

  const handleSubmitCourse = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!courseTitle.trim()) {
      toast.warning('Please enter a course title.');
      return;
    }

    setSubmitting(true);
    const courseType = parentCourseId ? 'sub_course' : 'full_level';
    const slug = courseTitle.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, '');

    const payload = {
      title: courseTitle,
      level: courseLevel,
      courseType,
      slug,
      description: courseDescription,
      parentCourse: parentCourseId || null,
      regularPrice: Number(regularPrice),
      offerPrice: offerPrice ? Number(offerPrice) : null,
      validityMonths: Number(validityMonths),
      isPublished,
    };

    let res;
    if (editingCourse) {
      res = await apiRequest(`/courses/${editingCourse._id}`, {
        method: 'PUT',
        body: JSON.stringify(payload),
      });
    } else {
      res = await apiRequest('/courses', {
        method: 'POST',
        body: JSON.stringify(payload),
      });
    }

    setSubmitting(false);

    if (res.success) {
      toast.success(editingCourse ? 'Course updated successfully!' : 'Course created successfully!');
      onSuccess();
      onClose();
    } else {
      toast.error(res.error || 'Failed to save course');
    }
  };

  return (
    <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4 overflow-y-auto !m-0">
      <div className="bg-white max-w-2xl w-full rounded-2xl shadow-2xl border border-gray-200 overflow-hidden my-8">
        <div className="p-6 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">
            <FolderPlus className="w-5 h-5 text-amber-600" />
            <span>{editingCourse ? 'Edit Course' : 'Create New Course'}</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={handleSubmitCourse} className="p-6 space-y-5">
          <div className="space-y-4">
            <div>
              <label className="block text-xs font-bold uppercase text-gray-700 mb-1">
                Course Title <span className="text-red-500">*</span>
              </label>
              <input
                type="text"
                required
                value={courseTitle}
                onChange={(e) => setCourseTitle(e.target.value)}
                placeholder="e.g. German A1 Masterclass"
                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 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">
                  Course Structure / Parent Major Course
                </label>
                <select
                  value={parentCourseId}
                  onChange={(e) => setParentCourseId(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"
                >
                  <option value="">No Parent (Standalone Major Level Course)</option>
                  {allCourses
                    .filter((c) => !c.parentCourse && c._id !== editingCourse?._id)
                    .map((major) => (
                      <option key={major._id} value={major._id}>
                        {major.title}
                      </option>
                    ))}
                </select>
              </div>

              <div>
                <label className="block text-xs font-bold uppercase text-gray-700 mb-1">
                  Course Level <span className="text-red-500">*</span>
                </label>
                <select
                  value={courseLevel}
                  onChange={(e) => setCourseLevel(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"
                >
                  <option value="General">General / Other</option>
                  <option value="A1">A1 Level</option>
                  <option value="A2">A2 Level</option>
                  <option value="B1">B1 Level</option>
                  <option value="B2">B2 Level</option>
                </select>
              </div>
            </div>
          </div>

          {/* Pricing & Validity */}
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <div>
              <label className="block text-xs font-bold uppercase text-gray-700 mb-1">
                Regular Price (€) <span className="text-red-500">*</span>
              </label>
              <input
                type="number"
                min="0"
                required
                value={regularPrice}
                onChange={(e) => setRegularPrice(Number(e.target.value))}
                className="w-full px-3.5 py-2.5 rounded-xl border border-gray-300 text-sm font-semibold outline-none"
              />
            </div>

            <div>
              <label className="block text-xs font-bold uppercase text-gray-700 mb-1">
                Offer Price (€)
              </label>
              <input
                type="number"
                min="0"
                value={offerPrice || ''}
                onChange={(e) => setOfferPrice(e.target.value ? Number(e.target.value) : undefined)}
                className="w-full px-3.5 py-2.5 rounded-xl border border-gray-300 text-sm font-semibold outline-none"
              />
            </div>

            <div>
              <label className="block text-xs font-bold uppercase text-gray-700 mb-1">
                Validity (Months) <span className="text-red-500">*</span>
              </label>
              <input
                type="number"
                min="1"
                required
                value={validityMonths}
                onChange={(e) => setValidityMonths(Number(e.target.value))}
                className="w-full px-3.5 py-2.5 rounded-xl border border-gray-300 text-sm font-semibold outline-none"
              />
            </div>
          </div>

          <div>
            <label className="block text-xs font-bold uppercase text-gray-700 mb-1">
              Description
            </label>
            <textarea
              rows={3}
              value={courseDescription}
              onChange={(e) => setCourseDescription(e.target.value)}
              placeholder="Summary of course content and learning goals..."
              className="w-full px-3.5 py-2.5 rounded-xl border border-gray-300 text-xs font-semibold outline-none"
            />
          </div>

          <div className="flex items-center justify-end gap-3 pt-3 border-t border-gray-200">
            <button
              type="button"
              onClick={onClose}
              disabled={submitting}
              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}
              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...' : editingCourse ? 'Save Course' : 'Create Course'}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}
