'use client';

import React, { useState, useEffect, useMemo } from 'react';
import { apiRequest } from '@/lib/api';
import { toast } from '@/context/ToastContext';
import {
  X,
  ShoppingBag,
  UserCheck,
  BookOpen,
  Layers,
  FileText,
  ShieldAlert,
  CheckCircle2,
  DollarSign,
  CheckSquare,
  Square,
} from 'lucide-react';

export interface StudentOption {
  _id: string;
  name: string;
  email: string;
  phoneNumber?: string;
}

export interface CourseOption {
  _id: string;
  title: string;
  level?: string;
  courseType?: string;
  parentCourse?: { _id: string; title?: string } | string | null;
  regularPrice: number;
  offerPrice?: number;
}

export interface LessonOption {
  _id: string;
  course?: string | { _id: string };
  chapterNumber: number;
  title: string;
  description?: string;
  durationMinutes?: number;
  price?: number;
  order?: number;
}

interface CreateOrderModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
}

export default function CreateOrderModal({
  isOpen,
  onClose,
  onSuccess,
}: CreateOrderModalProps) {
  const [students, setStudents] = useState<StudentOption[]>([]);
  const [courses, setCourses] = useState<CourseOption[]>([]);
  const [loadingData, setLoadingData] = useState(false);

  // Form selections
  const [selectedStudentId, setSelectedStudentId] = useState<string>('');
  const [selectedMainCourseId, setSelectedMainCourseId] = useState<string>('');
  const [selectedSubCourseId, setSelectedSubCourseId] = useState<string>('');

  // Purchase Type: 'complete' (buy whole course, lessons = []) vs 'lessons' (select individual lessons)
  const [purchaseType, setPurchaseType] = useState<'complete' | 'lessons'>('complete');

  // Lessons state
  const [availableLessons, setAvailableLessons] = useState<LessonOption[]>([]);
  const [loadingLessons, setLoadingLessons] = useState<boolean>(false);
  const [selectedLessonIds, setSelectedLessonIds] = useState<string[]>([]);

  // Payment Bypass & Details
  const [paymentRequired, setPaymentRequired] = useState<boolean>(false);
  const [gateway, setGateway] = useState<string>('admin_bypass');
  const [customAmount, setCustomAmount] = useState<string>('');
  const [notes, setNotes] = useState<string>('');
  const [submitting, setSubmitting] = useState(false);

  // 1. Fetch initial data (Students & Courses)
  useEffect(() => {
    if (!isOpen) return;

    const fetchModalData = async () => {
      setLoadingData(true);
      const [studentsRes, coursesRes] = await Promise.all([
        apiRequest('/students?limit=100'),
        apiRequest('/courses'),
      ]);

      if (studentsRes.success && Array.isArray(studentsRes.students)) {
        setStudents(studentsRes.students);
      }
      if (coursesRes.success && Array.isArray(coursesRes.courses)) {
        setCourses(coursesRes.courses);
      }
      setLoadingData(false);
    };

    fetchModalData();
  }, [isOpen]);

  // Helper to extract parent ID string
  const getParentId = (course: CourseOption): string | null => {
    if (!course.parentCourse) return null;
    if (typeof course.parentCourse === 'string') return course.parentCourse;
    if (typeof course.parentCourse === 'object' && course.parentCourse._id) {
      return course.parentCourse._id;
    }
    return null;
  };

  // Main courses (top level: no parent)
  const mainCourses = useMemo(() => {
    return courses.filter((c) => !getParentId(c));
  }, [courses]);

  // Sub-courses belonging to the chosen main course
  const subCourses = useMemo(() => {
    if (!selectedMainCourseId) return [];
    return courses.filter((c) => getParentId(c) === selectedMainCourseId);
  }, [courses, selectedMainCourseId]);

  // Compulsory courseId to store (Sub-course if selected, otherwise Main course)
  const activeCourseId = selectedSubCourseId || selectedMainCourseId;

  const activeCourse = useMemo(() => {
    return courses.find((c) => c._id === activeCourseId) || null;
  }, [courses, activeCourseId]);

  // Reset sub-course and lesson choices when main course changes
  const handleMainCourseChange = (mainId: string) => {
    setSelectedMainCourseId(mainId);
    setSelectedSubCourseId('');
    setSelectedLessonIds([]);
  };

  // Reset lesson choices when sub-course changes
  const handleSubCourseChange = (subId: string) => {
    setSelectedSubCourseId(subId);
    setSelectedLessonIds([]);
  };

  // Fetch lessons whenever activeCourseId changes
  useEffect(() => {
    if (!activeCourseId) {
      setAvailableLessons([]);
      setSelectedLessonIds([]);
      return;
    }

    const fetchLessons = async () => {
      setLoadingLessons(true);
      const res = await apiRequest(`/lessons?courseId=${activeCourseId}`);
      if (res.success && Array.isArray(res.lessons)) {
        setAvailableLessons(res.lessons);
      } else {
        setAvailableLessons([]);
      }
      setLoadingLessons(false);
    };

    fetchLessons();
  }, [activeCourseId]);

  // Recalculate suggested total price based on purchase type
  useEffect(() => {
    if (!activeCourse) {
      setCustomAmount('');
      return;
    }

    if (purchaseType === 'complete') {
      const coursePrice = activeCourse.offerPrice ?? activeCourse.regularPrice;
      setCustomAmount(coursePrice.toString());
    } else {
      // Sum of selected lessons
      const total = selectedLessonIds.reduce((sum, lessonId) => {
        const found = availableLessons.find((l) => l._id === lessonId);
        return sum + (found?.price || 0);
      }, 0);
      setCustomAmount(total.toString());
    }
  }, [activeCourse, purchaseType, selectedLessonIds, availableLessons]);

  // Toggle lesson selection
  const handleToggleLesson = (lessonId: string) => {
    setSelectedLessonIds((prev) =>
      prev.includes(lessonId)
        ? prev.filter((id) => id !== lessonId)
        : [...prev, lessonId]
    );
  };

  const handleSelectAllLessons = () => {
    if (selectedLessonIds.length === availableLessons.length) {
      setSelectedLessonIds([]);
    } else {
      setSelectedLessonIds(availableLessons.map((l) => l._id));
    }
  };

  // Toggle payment required
  const handlePaymentRequiredToggle = (enabled: boolean) => {
    setPaymentRequired(enabled);
    if (!enabled) {
      setGateway('admin_bypass');
    } else if (gateway === 'admin_bypass') {
      setGateway('stripe');
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!selectedStudentId) {
      toast.error('Please select a student.');
      return;
    }

    if (!activeCourseId) {
      toast.error('Please select a course.');
      return;
    }

    if (purchaseType === 'lessons' && selectedLessonIds.length === 0) {
      toast.error('Please select at least one lesson or choose "Buy Complete Course".');
      return;
    }

    setSubmitting(true);
    try {
      // Compulsory courseId
      // lessons array: empty if complete course, populated if individual lessons selected
      const payload = {
        studentId: selectedStudentId,
        courseId: activeCourseId,
        lessons: purchaseType === 'complete' ? [] : selectedLessonIds,
        paymentRequired,
        gateway: paymentRequired ? gateway : 'admin_bypass',
        amount: customAmount !== '' ? Number(customAmount) : undefined,
        notes: notes.trim(),
      };

      const res = await apiRequest('/orders', {
        method: 'POST',
        body: JSON.stringify(payload),
      });

      setSubmitting(false);

      if (res.success) {
        toast.success(
          paymentRequired
            ? 'Order created successfully!'
            : 'Order created with Payment Bypass! Student enrolled immediately.'
        );
        onSuccess();
        onClose();
      } else {
        toast.error(res.error || 'Failed to create order');
      }
    } catch (err: any) {
      setSubmitting(false);
      toast.error(err.message || 'Server error creating manual order');
    }
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 bg-black/60 backdrop-blur-xs flex items-center justify-center p-4 animate-fadeIn !m-0">
      <div className="bg-white max-w-4xl w-full rounded-3xl shadow-2xl border border-gray-100 p-6 sm:p-8 space-y-6 max-h-[92vh] overflow-y-auto relative">

        {/* Header */}
        <div className="flex items-center justify-between border-b border-gray-100 pb-4">
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded-2xl bg-[#FECE00] text-black font-black flex items-center justify-center shadow-xs">
              <ShoppingBag className="w-5 h-5" />
            </div>
            <div>
              <h3 className="text-xl font-extrabold text-gray-900">Create Manual Student Order</h3>
              <p className="text-xs text-gray-500 font-medium">Issue order on behalf of a student with optional payment bypass</p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="p-2 rounded-full text-gray-400 hover:text-gray-700 hover:bg-gray-100 transition cursor-pointer"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {loadingData ? (
          <div className="py-12 text-center space-y-3">
            <div className="w-8 h-8 border-3 border-[#FECE00] border-t-transparent rounded-full animate-spin mx-auto" />
            <p className="text-xs font-semibold text-gray-500">Loading student directory & courses...</p>
          </div>
        ) : (
          <form onSubmit={handleSubmit} className="space-y-6 text-xs sm:text-sm">

            {/* 1. Student Selection */}
            <div className="space-y-2">
              <label className="block font-extrabold text-gray-900 uppercase tracking-wider text-xs flex items-center gap-1.5">
                <UserCheck className="w-4 h-4 text-amber-600" />
                <span>1. Select Student <span className="text-red-500">*</span></span>
              </label>
              <select
                value={selectedStudentId}
                onChange={(e) => setSelectedStudentId(e.target.value)}
                className="w-full px-4 py-3 rounded-xl border border-gray-300 focus:border-[#FECE00] bg-white font-bold text-sm text-gray-900 outline-none shadow-2xs cursor-pointer"
                required
              >
                <option value="">-- Choose a Student --</option>
                {students.map((st) => (
                  <option key={st._id} value={st._id}>
                    {st.name} ({st.email}) {st.phoneNumber ? `- ${st.phoneNumber}` : ''}
                  </option>
                ))}
              </select>
              {students.length === 0 && (
                <p className="text-xs text-amber-700 italic">No registered students found.</p>
              )}
            </div>

            {/* 2 & 3. Main Course & Sub-Course Selection (Displayed side-by-side in 1 line) */}
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {/* Main Course Selection */}
              <div className="space-y-2">
                <label className="block font-extrabold text-gray-900 uppercase tracking-wider text-xs flex items-center gap-1.5 truncate">
                  <BookOpen className="w-4 h-4 text-amber-600 shrink-0" />
                  <span>2. Main Course Selection <span className="text-red-500">*</span></span>
                </label>
                <select
                  value={selectedMainCourseId}
                  onChange={(e) => handleMainCourseChange(e.target.value)}
                  className="w-full px-4 py-3 rounded-xl border border-gray-300 focus:border-[#FECE00] bg-white font-bold text-xs sm:text-sm text-gray-900 outline-none shadow-2xs cursor-pointer truncate"
                  required
                >
                  <option value="">-- Select Main Course --</option>
                  {mainCourses.map((c) => (
                    <option key={c._id} value={c._id}>
                      {c.title} {c.level ? `(Level ${c.level})` : ''} - €{c.offerPrice ?? c.regularPrice}
                    </option>
                  ))}
                </select>
              </div>

              {/* Sub-Course Selection */}
              <div className="space-y-2">
                <label className="block font-extrabold text-gray-900 uppercase tracking-wider text-xs flex items-center gap-1.5 truncate">
                  <Layers className="w-4 h-4 text-amber-600 shrink-0" />
                  <span>3. Sub-Course Selection {subCourses.length > 0 ? '(Optional)' : ''}</span>
                </label>
                {selectedMainCourseId ? (
                  subCourses.length > 0 ? (
                    <select
                      value={selectedSubCourseId}
                      onChange={(e) => handleSubCourseChange(e.target.value)}
                      className="w-full px-4 py-3 rounded-xl border border-amber-300 focus:border-[#FECE00] bg-amber-50/30 font-bold text-xs sm:text-sm text-gray-900 outline-none shadow-2xs cursor-pointer truncate"
                    >
                      <option value="">-- Main Course Default --</option>
                      {subCourses.map((sc) => (
                        <option key={sc._id} value={sc._id}>
                          {sc.title} - €{sc.offerPrice ?? sc.regularPrice}
                        </option>
                      ))}
                    </select>
                  ) : (
                    <div className="px-4 py-3 rounded-xl bg-gray-50 border border-gray-200 text-xs font-semibold text-gray-400 flex items-center h-[46px]">
                      No sub-courses (Main course active)
                    </div>
                  )
                ) : (
                  <div className="px-4 py-3 rounded-xl bg-gray-50 border border-gray-200 text-xs font-semibold text-gray-400 flex items-center h-[46px]">
                    Select a main course first
                  </div>
                )}
              </div>
            </div>

            {/* 4. Lessons Selection & Purchase Mode */}
            {activeCourseId && (
              <div className="space-y-3 p-4 rounded-xl border border-gray-200 bg-gray-50/50 animate-fadeIn">
                <label className="block font-extrabold text-gray-900 uppercase tracking-wider text-xs flex items-center gap-1.5">
                  <FileText className="w-4 h-4 text-amber-600" />
                  <span>4. Purchase Scope & Lessons Selection</span>
                </label>

                {/* Scope Radio options */}
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <label
                    className={`p-3 rounded-xl border cursor-pointer transition flex items-center gap-3 ${purchaseType === 'complete'
                      ? 'bg-amber-100/80 border-amber-500 font-extrabold text-gray-900'
                      : 'bg-white border-gray-200 text-gray-700 hover:border-amber-300'
                      }`}
                  >
                    <input
                      type="radio"
                      name="purchaseType"
                      value="complete"
                      checked={purchaseType === 'complete'}
                      onChange={() => {
                        setPurchaseType('complete');
                        setSelectedLessonIds([]);
                      }}
                      className="w-4 h-4 accent-black cursor-pointer"
                    />
                    <div>
                      <span className="text-xs font-extrabold block">Buy Complete Course</span>
                      <span className="text-[10px] text-gray-500 font-medium">Full course access (lessons array empty)</span>
                    </div>
                  </label>

                  <label
                    className={`p-3 rounded-xl border cursor-pointer transition flex items-center gap-3 ${purchaseType === 'lessons'
                      ? 'bg-amber-100/80 border-amber-500 font-extrabold text-gray-900'
                      : 'bg-white border-gray-200 text-gray-700 hover:border-amber-300'
                      }`}
                  >
                    <input
                      type="radio"
                      name="purchaseType"
                      value="lessons"
                      checked={purchaseType === 'lessons'}
                      onChange={() => setPurchaseType('lessons')}
                      className="w-4 h-4 accent-black cursor-pointer"
                    />
                    <div>
                      <span className="text-xs font-extrabold block">Select Specific Lessons</span>
                      <span className="text-[10px] text-gray-500 font-medium">Choose individual video lessons</span>
                    </div>
                  </label>
                </div>

                {/* Lessons Checkbox List if 'lessons' mode is chosen */}
                {purchaseType === 'lessons' && (
                  <div className="pt-2 space-y-2 animate-fadeIn">
                    <div className="flex items-center justify-between text-xs font-bold text-gray-700">
                      <span>Available Lessons ({availableLessons.length}):</span>
                      {availableLessons.length > 0 && (
                        <button
                          type="button"
                          onClick={handleSelectAllLessons}
                          className="text-[11px] text-amber-700 hover:underline font-extrabold cursor-pointer"
                        >
                          {selectedLessonIds.length === availableLessons.length ? 'Deselect All' : 'Select All'}
                        </button>
                      )}
                    </div>

                    {loadingLessons ? (
                      <div className="py-6 text-center text-xs text-gray-500 font-medium">
                        Loading course lessons...
                      </div>
                    ) : availableLessons.length === 0 ? (
                      <div className="p-3 rounded-xl bg-white border border-gray-200 text-xs text-amber-700 italic text-center">
                        No individual standalone lessons created for this course yet.
                      </div>
                    ) : (
                      <div className="max-h-48 overflow-y-auto space-y-1.5 pr-1">
                        {availableLessons.map((l) => {
                          const isSelected = selectedLessonIds.includes(l._id);
                          return (
                            <div
                              key={l._id}
                              onClick={() => handleToggleLesson(l._id)}
                              className={`p-2.5 rounded-xl border cursor-pointer transition flex items-center justify-between gap-3 text-xs ${isSelected
                                ? 'bg-amber-200/60 border-amber-500 font-extrabold text-gray-900'
                                : 'bg-white border-gray-200 hover:border-amber-300 text-gray-800'
                                }`}
                            >
                              <div className="flex items-center gap-2.5">
                                {isSelected ? (
                                  <CheckSquare className="w-4 h-4 text-amber-800 shrink-0" />
                                ) : (
                                  <Square className="w-4 h-4 text-gray-400 shrink-0" />
                                )}
                                <div>
                                  <span className="font-bold block text-gray-900">{l.title}</span>
                                  <span className="text-[10px] text-gray-500 font-medium">
                                    Chapter {l.chapterNumber} {l.durationMinutes ? `• ${l.durationMinutes} mins` : ''}
                                  </span>
                                </div>
                              </div>
                              <span className="font-black text-amber-900 shrink-0">€{l.price || 0}</span>
                            </div>
                          );
                        })}
                      </div>
                    )}
                  </div>
                )}
              </div>
            )}

            {/* 5. Payment & Amount Configuration */}
            <div className="p-3.5 rounded-xl bg-amber-50/40 border border-amber-200/80 space-y-2.5">
              <div className="flex flex-row items-center justify-between gap-3 pb-2 border-b border-amber-200/60">
                <div className="flex items-center gap-2">
                  <ShieldAlert className="w-4 h-4 text-amber-700 shrink-0" />
                  <span className="font-extrabold text-xs text-gray-900 uppercase tracking-wider">Payment Required</span>
                  {!paymentRequired ? (
                    <span className="px-2 py-0.5 rounded-full bg-emerald-500 text-white font-black text-[10px] uppercase flex items-center gap-1 shadow-2xs">
                      <CheckCircle2 className="w-3 h-3" />
                      Bypass Active
                    </span>
                  ) : (
                    <span className="px-2 py-0.5 rounded-full bg-gray-900 text-[#FECE00] font-black text-[10px]">
                      Required
                    </span>
                  )}
                </div>

                {/* Compact Inline Toggle Switch */}
                <div className="flex items-center gap-2 shrink-0">
                  <span className="text-[11px] font-bold text-gray-600 hidden sm:inline">
                    {paymentRequired ? 'Require Payment' : 'Bypass Payment'}
                  </span>
                  <button
                    type="button"
                    onClick={() => handlePaymentRequiredToggle(!paymentRequired)}
                    className={`w-11 h-6 rounded-full transition-colors p-0.5 flex items-center shrink-0 cursor-pointer ${paymentRequired ? 'bg-black justify-end' : 'bg-emerald-500 justify-start'
                      }`}
                  >
                    <div className="w-5 h-5 rounded-full bg-white shadow-xs" />
                  </button>
                </div>
              </div>

              {/* Gateway & Amount Inline */}
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                {paymentRequired && (
                  <div>
                    <label className="block font-bold text-gray-800 text-xs mb-1">Payment Gateway</label>
                    <select
                      value={gateway}
                      onChange={(e) => setGateway(e.target.value)}
                      className="w-full px-3 py-2 rounded-xl border border-gray-300 font-bold text-xs text-gray-900 outline-none bg-white"
                    >
                      <option value="stripe">Stripe</option>
                      <option value="paypal">PayPal</option>
                      <option value="bank_transfer">Bank Transfer</option>
                    </select>
                  </div>
                )}

                <div className={!paymentRequired ? 'col-span-2' : ''}>
                  <label className="block font-bold text-gray-800 text-xs mb-1 flex items-center justify-between">
                    <span>Order Total Amount (€)</span>
                    <span className="text-[10px] text-gray-400">Calculated or Override</span>
                  </label>
                  <div className="relative">
                    <DollarSign className="w-4 h-4 text-gray-400 absolute left-3 top-1/2 -translate-y-1/2" />
                    <input
                      type="number"
                      min="0"
                      step="0.01"
                      placeholder="0.00"
                      value={customAmount}
                      onChange={(e) => setCustomAmount(e.target.value)}
                      className="w-full pl-9 pr-4 py-2 rounded-xl border border-gray-300 font-bold text-xs text-gray-900 outline-none bg-white"
                    />
                  </div>
                </div>
              </div>
            </div>

            {/* 7. Optional Admin Notes */}
            <div>
              <label className="block font-bold text-gray-800 mb-1">Admin Order Notes (Optional)</label>
              <textarea
                rows={2}
                placeholder="Add any internal reason or reference notes for this order..."
                value={notes}
                onChange={(e) => setNotes(e.target.value)}
                className="w-full p-3 rounded-xl border border-gray-300 text-xs font-medium text-gray-900 outline-none bg-white resize-none"
              />
            </div>

            {/* Footer Form Buttons */}
            <div className="pt-3 border-t border-gray-100 flex items-center justify-end gap-3">
              <button
                type="button"
                onClick={onClose}
                className="px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 text-gray-700 font-extrabold text-xs transition cursor-pointer"
              >
                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 ? 'Processing...' : !paymentRequired ? 'Create Order (Payment Bypassed)' : 'Create Order'}
              </button>
            </div>
          </form>
        )}
      </div>
    </div>
  );
}
