import React, { useState, useEffect } from 'react';
import { useAppSelector } from '../store/hooks';
import { useNavigate } from 'react-router-dom';
import { 
  Play, 
  BookOpen, 
  Download, 
  ExternalLink, 
  CheckCircle, 
  Clock, 
  Users, 
  Award,
  Video,
  FileText,
  Headphones,
  Globe,
  ChevronDown,
  ChevronUp,
  Plus,
  Edit,
  Trash2,
  Settings,
  Save,
  X,
  Upload,
  Eye,
  EyeOff,
  Search,
  Filter
} from 'lucide-react';
import toast from 'react-hot-toast';

interface TrainingCourse {
  id: number;
  title: string;
  description: string;
  level: string;
  category: string;
  totalVideos: number;
  totalDuration: number;
  isActive: boolean;
  createdAt: string;
  vendor: {
    firstName: string;
    lastName: string;
    company?: string;
  };
  videos?: TrainingVideo[]; // Added for expanded view
}

interface TrainingVideo {
  id: number;
  title: string;
  description: string;
  videoType: 'youtube' | 'manual_upload';
  youtubeUrl?: string;
  videoFile?: string;
  duration: number;
  requiredForCompletion: boolean;
  sortOrder: number;
}

interface CourseProgress {
  courseId: number;
  status: 'not_started' | 'in_progress' | 'completed';
  progressPercentage: number;
  completedVideos: number;
  totalVideos: number;
  lastActivity?: string;
}

const Training: React.FC = () => {
  const { user } = useAppSelector((state) => state.auth);
  const navigate = useNavigate();
  const [courses, setCourses] = useState<TrainingCourse[]>([]);
  const [courseProgress, setCourseProgress] = useState<CourseProgress[]>([]);
  const [selectedCourse, setSelectedCourse] = useState<TrainingCourse | null>(null);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [selectedLevel, setSelectedLevel] = useState<string>('all');
  const [expandedCourse, setExpandedCourse] = useState<number | null>(null);
  
  // Modal states
  const [isCreateCourseModalOpen, setIsCreateCourseModalOpen] = useState(false);
  const [isAddVideoModalOpen, setIsAddVideoModalOpen] = useState(false);
  const [isEditCourseModalOpen, setIsEditCourseModalOpen] = useState(false);
  const [isVideoPreviewModalOpen, setIsVideoPreviewModalOpen] = useState(false);
  const [selectedVideo, setSelectedVideo] = useState<TrainingVideo | null>(null);
  
  // Form states
  const [courseForm, setCourseForm] = useState({
    title: '',
    description: '',
      level: 'Beginner',
    category: '',
    completionCriteria: 'all_videos',
    completionPercentage: 100
  });
  
  const [videoForm, setVideoForm] = useState({
    title: '',
    description: '',
    videoType: 'youtube' as 'youtube' | 'manual_upload',
    youtubeUrl: '',
    requiredForCompletion: true
  });

  useEffect(() => {
    console.log('Training component - User state:', user);
    console.log('Training component - User role:', user?.role);
    console.log('Training component - User roles:', user?.roles);
    console.log('Training component - Is authenticated:', !!localStorage.getItem('accessToken'));
    
    if (!user) {
      console.log('No user found, checking if we need to redirect to login');
      // If no user but we have a token, we might need to fetch user data
      const token = localStorage.getItem('accessToken');
      if (token) {
        console.log('Token found but no user, might need to fetch user data');
        // You might want to dispatch an action to fetch user data here
      } else {
        console.log('No token, redirecting to login');
        navigate('/login');
        return;
      }
    }
    
    // Check if user has the right role for vendor access
    const isVendor = user?.role === 'channel_partner_admin' || 
                     user?.roles?.some(r => r.name === 'channel_partner_admin');
    
    console.log('Is vendor:', isVendor);
    
    if (isVendor) {
      console.log('Fetching vendor courses...');
      fetchVendorCourses();
    } else {
      console.log('Fetching available courses for reseller...');
      fetchAvailableCourses();
    }
  }, [user, navigate]);

  const fetchVendorCourses = async () => {
    try {
      setLoading(true);
      const token = localStorage.getItem('accessToken');
      console.log('Fetching vendor courses with token:', token ? 'Token exists' : 'No token');
      
      if (!token) {
        console.error('No access token found');
        toast.error('Authentication required. Please log in.');
        return;
      }
      
      const response = await fetch(`${process.env.REACT_APP_API_URL || 'http://localhost:5000/api'}/training-new/courses`, {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      console.log('API response status:', response.status);
      console.log('API response headers:', response.headers);

      if (response.ok) {
        const data = await response.json();
        console.log('API response data:', data);
        console.log('Courses received:', data.data.courses);
        console.log('First course videos:', data.data.courses[0]?.videos);
        setCourses(data.data.courses || []);
      } else {
        const errorData = await response.json().catch(() => ({ message: 'Unknown error' }));
        console.error('API error response:', errorData);
        toast.error(errorData.message || 'Failed to fetch courses');
      }
    } catch (error) {
      console.error('Error fetching courses:', error);
      toast.error('Failed to fetch courses');
    } finally {
      setLoading(false);
    }
  };

  const fetchAvailableCourses = async () => {
    try {
      setLoading(true);
      const token = localStorage.getItem('accessToken');
      console.log('Fetching available courses with token:', token ? 'Token exists' : 'No token');
      
      if (!token) {
        console.error('No access token found');
        toast.error('Authentication required. Please log in.');
        return;
      }
      
      const response = await fetch(`${process.env.REACT_APP_API_URL || 'http://localhost:5000/api'}/training-new/courses`, {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      console.log('API response status:', response.status);
      console.log('API response headers:', response.headers);

      if (response.ok) {
        const data = await response.json();
        console.log('API response data:', data);
        console.log('Courses received:', data.data.courses);
        console.log('First course videos:', data.data.courses[0]?.videos);
        setCourses(data.data.courses || []);
        
        // Fetch progress for each course
        const progressPromises = data.data.courses.map((course: TrainingCourse) => 
          fetchCourseProgress(course.id)
        );
        
        const progressResults = await Promise.all(progressPromises);
        setCourseProgress(progressResults.filter(Boolean));
      } else {
        const errorData = await response.json().catch(() => ({ message: 'Unknown error' }));
        console.error('API error response:', errorData);
        toast.error(errorData.message || 'Failed to fetch courses');
      }
    } catch (error) {
      console.error('Error fetching courses:', error);
      toast.error('Failed to fetch courses');
    } finally {
      setLoading(false);
    }
  };

  const fetchCourseProgress = async (courseId: number): Promise<CourseProgress | null> => {
    try {
      const token = localStorage.getItem('accessToken');
      const response = await fetch(`${process.env.REACT_APP_API_URL || 'http://localhost:5000/api'}/training-new/courses/${courseId}/progress`, {
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        }
      });

      if (response.ok) {
        const data = await response.json();
        return data.data.userProgress || null;
      }
    } catch (error) {
      console.error('Error fetching course progress:', error);
    }
    return null;
  };

  const handleCreateCourse = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const token = localStorage.getItem('accessToken');
      const response = await fetch(`${process.env.REACT_APP_API_URL || 'http://localhost:5000/api'}/training-new/courses`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(courseForm)
      });

      if (response.ok) {
        const data = await response.json();
        toast.success('Course created successfully');
        setIsCreateCourseModalOpen(false);
        setCourseForm({
          title: '',
          description: '',
          level: 'Beginner',
          category: '',
          completionCriteria: 'all_videos',
          completionPercentage: 100
        });
        fetchVendorCourses();
      } else {
        const errorData = await response.json();
        toast.error(errorData.message || 'Failed to create course');
      }
    } catch (error) {
      console.error('Error creating course:', error);
      toast.error('Failed to create course');
    }
  };

  const handleAddVideo = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedCourse) return;

    try {
      const token = localStorage.getItem('accessToken');
      const formData = new FormData();
      
      // Handle form data properly for different types
      Object.keys(videoForm).forEach(key => {
        const value = videoForm[key as keyof typeof videoForm];
        if (typeof value === 'string') {
          formData.append(key, value);
        } else if (typeof value === 'boolean') {
          formData.append(key, value.toString());
        }
      });

      const response = await fetch(`${process.env.REACT_APP_API_URL || 'http://localhost:5000/api'}/training-new/courses/${selectedCourse.id}/videos`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`
        },
        body: formData
      });

      if (response.ok) {
        const data = await response.json();
        toast.success('Video added successfully');
        setIsAddVideoModalOpen(false);
        setVideoForm({
          title: '',
          description: '',
          videoType: 'youtube',
          youtubeUrl: '',
          requiredForCompletion: true
        });
        fetchVendorCourses();
      } else {
        const errorData = await response.json();
        toast.error(errorData.message || 'Failed to add video');
      }
    } catch (error) {
      console.error('Error adding video:', error);
      toast.error('Failed to add video');
    }
  };

  const getLevelColor = (level: string) => {
    switch (level) {
      case 'Beginner': return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200';
      case 'Intermediate': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200';
      case 'Advanced': return 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200';
      default: return 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200';
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200';
      case 'in_progress': return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200';
      case 'not_started': return 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200';
      default: return 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200';
    }
  };

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'completed': return <CheckCircle className="w-5 h-5 text-green-600" />;
      case 'in_progress': return <Clock className="w-5 h-5 text-yellow-600" />;
      default: return <Play className="w-5 h-5 text-gray-400" />;
    }
  };

  const filteredCourses = courses.filter(course => {
    const matchesSearch = course.title.toLowerCase().includes(search.toLowerCase()) ||
                         course.description.toLowerCase().includes(search.toLowerCase());
    const matchesCategory = selectedCategory === 'all' || course.category === selectedCategory;
    const matchesLevel = selectedLevel === 'all' || course.level === selectedLevel;
    
    return matchesSearch && matchesCategory && matchesLevel;
  });

  const uniqueCategories = Array.from(new Set(courses.map(course => course.category).filter(Boolean)));
  const uniqueLevels = ['Beginner', 'Intermediate', 'Advanced'];

  if (loading) {
  return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-primary-600"></div>
          </div>
    );
  }

  return (
    <div className="p-6 space-y-8">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-secondary-900 dark:text-white mb-3">
              Training Center
            </h1>
        <p className="text-secondary-600 dark:text-secondary-400 text-lg">
              Master the Cloudtopiaa platform and maximize your success
            </p>
          </div>

      {/* Action Bar for Vendors */}
      {user?.role === 'channel_partner_admin' && (
        <div className="flex justify-between items-center mb-6">
          <div className="text-sm text-gray-600 dark:text-gray-400">
            {courses.length} course{courses.length !== 1 ? 's' : ''} created
        </div>
            <button
            onClick={() => setIsCreateCourseModalOpen(true)}
            className="btn btn-primary"
          >
            <Plus className="w-4 h-4 mr-2" />
            Create Course
            </button>
          </div>
      )}

      {/* Search and Filters */}
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 p-6">
        <div className="flex flex-col lg:flex-row gap-4 items-center justify-between">
          <div className="flex flex-col sm:flex-row gap-4 flex-1">
            <form onSubmit={(e) => e.preventDefault()} className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
                <input
                  type="text"
                  placeholder="Search courses..."
                  value={search}
                  onChange={(e) => setSearch(e.target.value)}
                  className="w-full pl-10 pr-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
                />
              </div>
            </form>

            <div className="flex items-center space-x-2">
              <Filter className="w-4 h-4 text-gray-400" />
              <select
                value={selectedCategory}
                onChange={(e) => setSelectedCategory(e.target.value)}
                className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
              >
                <option value="all">All Categories</option>
                {uniqueCategories.map((category) => (
                  <option key={category} value={category}>
                    {category}
                  </option>
                ))}
              </select>

              <select
                value={selectedLevel}
                onChange={(e) => setSelectedLevel(e.target.value)}
                className="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
              >
                <option value="all">All Levels</option>
                {uniqueLevels.map((level) => (
                  <option key={level} value={level}>
                    {level}
                  </option>
                ))}
              </select>
            </div>
          </div>
        </div>
      </div>

      {/* How Training Works Section */}
      <div className="bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 p-6">
        <h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-6">
          How Training Works
        </h2>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div className="text-center">
            <div className="w-16 h-16 bg-blue-100 dark:bg-blue-900 rounded-full flex items-center justify-center mx-auto mb-4">
              <BookOpen className="w-8 h-8 text-blue-600 dark:text-blue-400" />
                </div>
            <div className="text-2xl font-bold text-blue-600 dark:text-blue-400 mb-2">1</div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
              Choose Your Path
            </h3>
            <p className="text-gray-600 dark:text-gray-400">
              Select from beginner, intermediate, or advanced training modules based on your experience level.
            </p>
              </div>

              <div className="text-center">
            <div className="w-16 h-16 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center mx-auto mb-4">
              <Video className="w-8 h-8 text-green-600 dark:text-green-400" />
                </div>
            <div className="text-2xl font-bold text-green-600 dark:text-green-400 mb-2">2</div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
              Watch & Learn
            </h3>
            <p className="text-gray-600 dark:text-gray-400">
              Access high-quality video tutorials, webinars, and interactive content designed for resellers.
            </p>
              </div>

              <div className="text-center">
            <div className="w-16 h-16 bg-orange-100 dark:bg-orange-900 rounded-full flex items-center justify-center mx-auto mb-4">
              <Award className="w-8 h-8 text-orange-600 dark:text-orange-400" />
                </div>
            <div className="text-2xl font-bold text-orange-600 dark:text-orange-400 mb-2">3</div>
            <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
              Get Certified
            </h3>
            <p className="text-gray-600 dark:text-gray-400">
              Complete assessments and earn certifications to demonstrate your expertise to customers.
            </p>
              </div>
            </div>
          </div>

      {/* Training Courses */}
      <div className="space-y-6">
        <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
          Training Modules
        </h2>

        {filteredCourses.length > 0 ? (
          <div className="space-y-4">
            {filteredCourses.map((course) => {
              const progress = courseProgress.find(p => p.courseId === course.id);
              const status = progress ? progress.status : 'not_started';
              const progressPercentage = progress ? progress.progressPercentage : 0;
              const isExpanded = expandedCourse === course.id;

              return (
                <div key={course.id} className="bg-white dark:bg-gray-800 rounded-xl shadow-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
                  <div className="p-6">
                    <div className="flex items-start justify-between">
                      <div className="flex-1">
                        <div className="flex items-center space-x-3 mb-3">
                          <h3 className="text-lg font-semibold text-gray-900 dark:text-white">
                            {course.title}
                          </h3>
                          <span className={`px-2 py-1 rounded-full text-xs font-medium ${getLevelColor(course.level)}`}>
                            {course.level}
                          </span>
                          {user?.role !== 'channel_partner_admin' && (
                            <div className="flex items-center space-x-2">
                              {getStatusIcon(status)}
                              <span className={`px-2 py-1 rounded-full text-xs font-medium ${getStatusColor(status)}`}>
                                {status.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase())}
                          </span>
                        </div>
                          )}
                        </div>
                        
                        <p className="text-gray-600 dark:text-gray-400 mb-4">
                          {course.description}
                        </p>

                        <div className="flex items-center space-x-6 text-sm text-gray-500 dark:text-gray-400">
                          <div className="flex items-center space-x-1">
                            <Clock className="w-4 h-4" />
                            <span>{Math.round(course.totalDuration / 60)} hours</span>
                          </div>
                          <div className="flex items-center space-x-1">
                            <Video className="w-4 h-4" />
                            <span>{course.totalVideos} videos</span>
                          </div>
                          <div className="flex items-center space-x-1">
                            <FileText className="w-4 h-4" />
                            <span>{course.totalVideos} materials</span>
                          </div>
                          {user?.role !== 'channel_partner_admin' && progress && (
                            <div className="flex items-center space-x-1">
                              <CheckCircle className="w-4 h-4" />
                              <span>{progressPercentage}% complete</span>
                        </div>
                          )}
                      </div>

                        {user?.role !== 'channel_partner_admin' && progress && (
                          <div className="mt-4">
                            <div className="flex items-center justify-between text-sm mb-2">
                              <span className="text-gray-600 dark:text-gray-400">Progress</span>
                              <span className="text-gray-900 dark:text-white font-medium">
                                {progressPercentage}%
                              </span>
                    </div>
                            <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                              <div 
                                className="bg-primary-600 h-2 rounded-full transition-all duration-300"
                                style={{ width: `${progressPercentage}%` }}
                              ></div>
                            </div>
                          </div>
                        )}
                      </div>

                      <div className="flex items-center space-x-2 ml-4">
                        {user?.role === 'channel_partner_admin' && (
                          <>
                          <button
                              onClick={() => {
                                setSelectedCourse(course);
                                setIsEditCourseModalOpen(true);
                              }}
                              className="p-2 text-gray-400 hover:text-blue-600 transition-colors"
                              title="Edit Course"
                          >
                            <Edit className="w-4 h-4" />
                          </button>
                          <button
                              onClick={() => {
                                setSelectedCourse(course);
                                setIsAddVideoModalOpen(true);
                              }}
                              className="p-2 text-gray-400 hover:text-green-600 transition-colors"
                              title="Add Video"
                            >
                              <Plus className="w-4 h-4" />
                          </button>
                          </>
                        )}
                        <button
                          onClick={() => setExpandedCourse(isExpanded ? null : course.id)}
                          className="p-2 text-gray-400 hover:text-gray-600 transition-colors"
                          title={isExpanded ? "Collapse" : "Expand"}
                        >
                          {isExpanded ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />}
                        </button>
                  </div>
                </div>

                {/* Expanded Content */}
                    {isExpanded && (
                      <div className="mt-6 pt-6 border-t border-gray-200 dark:border-gray-700">
                        <div className="space-y-4">
                          <h4 className="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                            Course Content
                        </h4>
                          
                          {/* Debug info */}
                          <div className="bg-gray-100 dark:bg-gray-700 p-4 rounded-lg text-sm">
                            <p><strong>Debug Info:</strong></p>
                            <p>Course ID: {course.id}</p>
                            <p>Videos count: {course.videos?.length || 0}</p>
                            <p>Videos data: {JSON.stringify(course.videos, null, 2)}</p>
                      </div>
                          
                          {/* Video List */}
                          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                            {course.videos && course.videos.length > 0 ? (
                              course.videos.map((video) => (
                                <div key={video.id} className="bg-gray-50 dark:bg-gray-700 rounded-lg p-4 border border-gray-200 dark:border-gray-600">
                                  {/* Video Thumbnail/Preview */}
                                  <div className="relative mb-3">
                                    {video.videoType === 'youtube' && video.youtubeUrl ? (
                                      <div className="aspect-video bg-gray-200 dark:bg-gray-600 rounded-lg overflow-hidden">
                                        <img
                                          src={`https://img.youtube.com/vi/${video.youtubeUrl?.split('v=')[1] || ''}/maxresdefault.jpg`}
                                alt={video.title}
                                className="w-full h-full object-cover"
                                          onError={(e) => {
                                            // Fallback to medium quality if maxresdefault fails
                                            const target = e.target as HTMLImageElement;
                                            const videoId = video.youtubeUrl?.split('v=')[1] || '';
                                            target.src = `https://img.youtube.com/vi/${videoId}/mqdefault.jpg`;
                                          }}
                                        />
                                        {/* Play Button Overlay */}
                                        <div 
                                          className="absolute inset-0 flex items-center justify-center bg-black bg-opacity-20 hover:bg-opacity-30 transition-all cursor-pointer"
                                          onClick={() => {
                                            setSelectedVideo(video);
                                            setIsVideoPreviewModalOpen(true);
                                          }}
                                        >
                                          <div className="w-16 h-16 bg-red-600 rounded-full flex items-center justify-center hover:bg-red-700 transition-colors">
                                            <Play className="w-8 h-8 text-white ml-1" />
                              </div>
                            </div>
                                      </div>
                                    ) : video.videoFile ? (
                                      <div className="aspect-video bg-gray-200 dark:bg-gray-600 rounded-lg overflow-hidden flex items-center justify-center">
                                        <video
                                          className="w-full h-full object-cover"
                                          preload="metadata"
                                        >
                                          <source src={video.videoFile} type="video/mp4" />
                                          Your browser does not support the video tag.
                                        </video>
                                        {/* Play Button Overlay */}
                                        <div 
                                          className="absolute inset-0 flex items-center justify-center bg-black bg-opacity-20 hover:bg-opacity-30 transition-all cursor-pointer"
                                          onClick={() => {
                                            setSelectedVideo(video);
                                            setIsVideoPreviewModalOpen(true);
                                          }}
                                        >
                                          <div className="w-16 h-16 bg-blue-600 rounded-full flex items-center justify-center hover:bg-blue-700 transition-colors">
                                            <Play className="w-8 h-8 text-white ml-1" />
                                </div>
                              </div>
                            </div>
                                    ) : (
                                      <div className="aspect-video bg-gray-200 dark:bg-gray-600 rounded-lg overflow-hidden flex items-center justify-center">
                                        <Video className="w-12 h-12 text-gray-400" />
                          </div>
                                    )}
                                    
                                    {/* Video Duration Badge */}
                                    {video.duration && (
                                      <div className="absolute bottom-2 right-2 bg-black bg-opacity-75 text-white text-xs px-2 py-1 rounded">
                                        {Math.floor(video.duration / 60)}:{(video.duration % 60).toString().padStart(2, '0')}
                      </div>
                                    )}
                                    
                                    {/* Required Badge */}
                                    {video.requiredForCompletion && (
                                      <div className="absolute top-2 left-2 bg-red-500 text-white text-xs px-2 py-1 rounded">
                                        Required
                                      </div>
                                    )}
                    </div>

                                  {/* Video Info */}
                    <div>
                                    <h5 className="font-medium text-gray-900 dark:text-white mb-1">
                                      {video.title}
                                    </h5>
                                    {video.description && (
                                      <p className="text-sm text-gray-600 dark:text-gray-400 mb-2">
                                        {video.description}
                                      </p>
                                    )}
                                    
                                    {/* Video Type Badge */}
                                    <div className="flex items-center justify-between">
                                      <span className={`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${
                                        video.videoType === 'youtube' 
                                          ? 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
                                          : 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'
                                      }`}>
                                        {video.videoType === 'youtube' ? (
                                          <>
                                            <svg className="w-3 h-3 mr-1" viewBox="0 0 24 24" fill="currentColor">
                                              <path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z"/>
                                            </svg>
                                            YouTube
                                          </>
                                        ) : (
                                          <>
                                            <Upload className="w-3 h-3 mr-1" />
                                            Uploaded
                                          </>
                                        )}
                                      </span>
                                      
                                      {/* Play Button */}
                          <button
                            onClick={() => {
                                          setSelectedVideo(video);
                                          setIsVideoPreviewModalOpen(true);
                            }}
                                        className="inline-flex items-center px-3 py-1 bg-primary-600 text-white text-sm rounded-md hover:bg-primary-700 transition-colors"
                          >
                                        <Play className="w-3 h-3 mr-1" />
                                        Play
                          </button>
                      </div>
                                </div>
                              </div>
                              ))
                            ) : (
                              <div className="col-span-full text-center py-8">
                                <Video className="w-16 h-16 mx-auto mb-4 text-gray-400" />
                                <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
                                  No videos added yet
                                </h3>
                                <p className="text-gray-500 dark:text-gray-400 mb-4">
                                  {user?.role === 'channel_partner_admin' 
                                    ? 'Add videos to this course to get started'
                                    : 'This course will have videos added soon'
                                  }
                                </p>
                                {user?.role === 'channel_partner_admin' && (
                                        <button
                                    onClick={() => {
                                      setSelectedCourse(course);
                                      setIsAddVideoModalOpen(true);
                                    }}
                                    className="btn btn-primary"
                                  >
                                    <Plus className="w-4 h-4 mr-2" />
                                    Add Video
                                        </button>
                                    )}
                                  </div>
                            )}
                                </div>
                              </div>
                            </div>
                    )}
                          </div>
                      </div>
              );
            })}
                    </div>
        ) : (
          <div className="text-center py-12">
            <div className="w-16 h-16 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center mx-auto mb-4">
              <BookOpen className="w-8 h-8 text-gray-400" />
                  </div>
            <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-2">
              {search || selectedCategory !== 'all' || selectedLevel !== 'all' 
                ? 'No courses found' 
                : 'No courses available yet'}
            </h3>
            <p className="text-gray-500 dark:text-gray-400 mb-6">
              {search || selectedCategory !== 'all' || selectedLevel !== 'all'
                ? 'Try adjusting your search or filters'
                : user?.role === 'channel_partner_admin'
                  ? 'Create your first training course to get started'
                  : 'Check back later for new training courses'}
            </p>
            {user?.role === 'channel_partner_admin' && (
              <button
                onClick={() => setIsCreateCourseModalOpen(true)}
                className="btn btn-primary"
              >
                <Plus className="w-4 h-4 mr-2" />
                Create Your First Course
              </button>
                )}
              </div>
        )}
          </div>

      {/* Create Course Modal */}
      {isCreateCourseModalOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl max-w-md w-full">
            <div className="p-6">
              <h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-4">
                Create New Course
              </h2>
              
              <form onSubmit={handleCreateCourse} className="space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Course Title
                  </label>
                  <input
                    type="text"
                    value={courseForm.title}
                    onChange={(e) => setCourseForm({ ...courseForm, title: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
                    required
                  />
      </div>

              <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Description
                  </label>
                  <textarea
                    value={courseForm.description}
                    onChange={(e) => setCourseForm({ ...courseForm, description: e.target.value })}
                    rows={3}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
                  />
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Level
                    </label>
                    <select
                      value={courseForm.level}
                      onChange={(e) => setCourseForm({ ...courseForm, level: e.target.value })}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
                    >
                      <option value="Beginner">Beginner</option>
                      <option value="Intermediate">Intermediate</option>
                      <option value="Advanced">Advanced</option>
                  </select>
                </div>

              <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Category
                    </label>
                    <input
                      type="text"
                      value={courseForm.category}
                      onChange={(e) => setCourseForm({ ...courseForm, category: e.target.value })}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
                      placeholder="e.g., Sales, Technical"
                    />
              </div>
              </div>

                <div className="flex space-x-3 pt-4">
                <button
                  type="button"
                    onClick={() => setIsCreateCourseModalOpen(false)}
                    className="flex-1 btn btn-outline"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                    className="flex-1 btn btn-primary"
                >
                    Create Course
                </button>
              </div>
            </form>
            </div>
          </div>
        </div>
      )}

      {/* Add Video Modal */}
      {isAddVideoModalOpen && selectedCourse && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl max-w-md w-full">
            <div className="p-6">
              <h2 className="text-xl font-semibold text-gray-900 dark:text-white mb-4">
                Add Video to {selectedCourse.title}
              </h2>
              
              <form onSubmit={handleAddVideo} className="space-y-4">
              <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Video Title
                  </label>
                  <input
                    type="text"
                    value={videoForm.title}
                    onChange={(e) => setVideoForm({ ...videoForm, title: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
                    required
                  />
              </div>

              <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Description
                  </label>
                  <textarea
                    value={videoForm.description}
                    onChange={(e) => setVideoForm({ ...videoForm, description: e.target.value })}
                    rows={3}
                    className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
                  />
              </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                    Video Type
                  </label>
                  <div className="space-y-2">
                    <label className="flex items-center">
                      <input
                        type="radio"
                        value="youtube"
                        checked={videoForm.videoType === 'youtube'}
                        onChange={(e) => setVideoForm({ ...videoForm, videoType: e.target.value as 'youtube' | 'manual_upload' })}
                        className="mr-2"
                      />
                      <span className="text-sm text-gray-700 dark:text-gray-300">YouTube Link</span>
                    </label>
                    <label className="flex items-center">
                      <input
                        type="radio"
                        value="manual_upload"
                        checked={videoForm.videoType === 'manual_upload'}
                        onChange={(e) => setVideoForm({ ...videoForm, videoType: e.target.value as 'youtube' | 'manual_upload' })}
                        className="mr-2"
                      />
                      <span className="text-sm text-gray-700 dark:text-gray-300">Manual Upload</span>
                    </label>
                </div>
                </div>

                {videoForm.videoType === 'youtube' && (
              <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      YouTube URL
                    </label>
                    <input
                      type="url"
                      value={videoForm.youtubeUrl}
                      onChange={(e) => setVideoForm({ ...videoForm, youtubeUrl: e.target.value })}
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
                      placeholder="https://www.youtube.com/watch?v=..."
                      required
                    />
        </div>
      )}

                {videoForm.videoType === 'manual_upload' && (
              <div>
                    <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                      Video File
                    </label>
                    <input
                      type="file"
                      accept="video/*"
                      className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-primary-500"
                      required
                    />
                    <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                      Supported formats: MP4, AVI, MOV, WMV, FLV (Max: 500MB)
                    </p>
              </div>
                )}

              <div>
                  <label className="flex items-center">
                    <input
                      type="checkbox"
                      checked={videoForm.requiredForCompletion}
                      onChange={(e) => setVideoForm({ ...videoForm, requiredForCompletion: e.target.checked })}
                      className="mr-2"
                    />
                    <span className="text-sm text-gray-700 dark:text-gray-300">
                      Required for course completion
                    </span>
                  </label>
              </div>

                <div className="flex space-x-3 pt-4">
                <button
                  type="button"
                    onClick={() => setIsAddVideoModalOpen(false)}
                    className="flex-1 btn btn-outline"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                    className="flex-1 btn btn-primary"
                >
                    Add Video
                </button>
              </div>
            </form>
            </div>
          </div>
        </div>
      )}

      {/* Video Preview Modal */}
      {isVideoPreviewModalOpen && selectedVideo && (
        <div className="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50 p-4">
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl max-w-4xl w-full max-h-[90vh] overflow-hidden">
            <div className="p-6">
              <div className="flex items-center justify-between mb-4">
                <h2 className="text-xl font-semibold text-gray-900 dark:text-white">
                  {selectedVideo.title}
                </h2>
                <button
                  onClick={() => setIsVideoPreviewModalOpen(false)}
                  className="p-2 text-gray-400 hover:text-gray-600 transition-colors"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>
              
              {/* Video Player */}
              <div className="mb-4">
                {selectedVideo.videoType === 'youtube' && selectedVideo.youtubeUrl ? (
                  <div className="aspect-video bg-gray-200 dark:bg-gray-600 rounded-lg overflow-hidden">
                    <iframe
                      src={selectedVideo.youtubeUrl.replace('watch?v=', 'embed/')}
                      title={selectedVideo.title}
                      className="w-full h-full"
                      frameBorder="0"
                      allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                      allowFullScreen
                    />
          </div>
                ) : selectedVideo.videoFile ? (
                  <div className="aspect-video bg-gray-200 dark:bg-gray-600 rounded-lg overflow-hidden">
                    <video
                      className="w-full h-full"
                      controls
                      autoPlay
                    >
                      <source src={selectedVideo.videoFile} type="video/mp4" />
                      Your browser does not support the video tag.
                    </video>
                  </div>
                ) : (
                  <div className="aspect-video bg-gray-200 dark:bg-gray-600 rounded-lg flex items-center justify-center">
                    <Video className="w-16 h-16 text-gray-400" />
                    <p className="text-gray-500 dark:text-gray-400 ml-3">Video not available</p>
        </div>
      )}
              </div>
              
              {/* Video Details */}
              <div className="space-y-3">
                {selectedVideo.description && (
              <div>
                    <h3 className="font-medium text-gray-900 dark:text-white mb-2">Description</h3>
                    <p className="text-gray-600 dark:text-gray-400">{selectedVideo.description}</p>
              </div>
                )}
                
                <div className="grid grid-cols-2 gap-4 text-sm">
              <div>
                    <span className="font-medium text-gray-900 dark:text-white">Type:</span>
                    <span className={`ml-2 px-2 py-1 rounded-full text-xs font-medium ${
                      selectedVideo.videoType === 'youtube' 
                        ? 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200'
                        : 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200'
                    }`}>
                      {selectedVideo.videoType === 'youtube' ? 'YouTube' : 'Uploaded'}
                    </span>
              </div>
                  
                  {selectedVideo.duration && (
                <div>
                      <span className="font-medium text-gray-900 dark:text-white">Duration:</span>
                      <span className="ml-2 text-gray-600 dark:text-gray-400">
                        {Math.floor(selectedVideo.duration / 60)}:{(selectedVideo.duration % 60).toString().padStart(2, '0')}
                      </span>
                </div>
                  )}
                  
                <div>
                    <span className="font-medium text-gray-900 dark:text-white">Required:</span>
                    <span className={`ml-2 px-2 py-1 rounded-full text-xs font-medium ${
                      selectedVideo.requiredForCompletion
                        ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200'
                        : 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200'
                    }`}>
                      {selectedVideo.requiredForCompletion ? 'Yes' : 'No'}
                    </span>
                </div>
              </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Training; 