/**
 * CreatorDashboard Component
 * Dashboard for course creators with analytics and content management
 * Epic: OQI-002 Modulo Educativo
 */

import React, { useState, useMemo } from 'react';
import {
  AcademicCapIcon,
  PlayCircleIcon,
  UsersIcon,
  CurrencyDollarIcon,
  ChartBarIcon,
  PlusIcon,
  PencilIcon,
  EyeIcon,
  TrashIcon,
  ArrowPathIcon,
  StarIcon,
  ClockIcon,
  ArrowTrendingUpIcon,
  ArrowTrendingDownIcon,
  FunnelIcon,
  MagnifyingGlassIcon,
} from '@heroicons/react/24/solid';

// Types
export interface CreatorCourse {
  id: string;
  title: string;
  thumbnail?: string;
  status: 'draft' | 'published' | 'archived';
  studentsEnrolled: number;
  rating: number;
  reviewsCount: number;
  lessonsCount: number;
  totalDuration: number;
  revenue: number;
  completionRate: number;
  createdAt: Date;
  updatedAt: Date;
}

export interface CreatorStats {
  totalStudents: number;
  totalCourses: number;
  totalRevenue: number;
  avgRating: number;
  totalViews: number;
  totalCompletions: number;
  revenueChange: number;
  studentsChange: number;
}

export interface RecentActivity {
  id: string;
  type: 'enrollment' | 'review' | 'completion' | 'revenue';
  message: string;
  timestamp: Date;
  courseId?: string;
  courseName?: string;
}

interface CreatorDashboardProps {
  stats: CreatorStats;
  courses: CreatorCourse[];
  recentActivity: RecentActivity[];
  onCreateCourse?: () => void;
  onEditCourse?: (courseId: string) => void;
  onViewCourse?: (courseId: string) => void;
  onDeleteCourse?: (courseId: string) => void;
  onRefresh?: () => void;
  isLoading?: boolean;
  compact?: boolean;
}

type CourseFilter = 'all' | 'published' | 'draft' | 'archived';
type SortOption = 'newest' | 'popular' | 'revenue' | 'rating';

const CreatorDashboard: React.FC<CreatorDashboardProps> = ({
  stats,
  courses,
  recentActivity,
  onCreateCourse,
  onEditCourse,
  onViewCourse,
  onDeleteCourse,
  onRefresh,
  isLoading = false,
  compact = false,
}) => {
  const [filter, setFilter] = useState<CourseFilter>('all');
  const [sortBy, setSortBy] = useState<SortOption>('newest');
  const [searchQuery, setSearchQuery] = useState('');

  // Filter and sort courses
  const filteredCourses = useMemo(() => {
    let result = [...courses];

    // Filter by status
    if (filter !== 'all') {
      result = result.filter((c) => c.status === filter);
    }

    // Search
    if (searchQuery) {
      const query = searchQuery.toLowerCase();
      result = result.filter((c) => c.title.toLowerCase().includes(query));
    }

    // Sort
    switch (sortBy) {
      case 'newest':
        result.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
        break;
      case 'popular':
        result.sort((a, b) => b.studentsEnrolled - a.studentsEnrolled);
        break;
      case 'revenue':
        result.sort((a, b) => b.revenue - a.revenue);
        break;
      case 'rating':
        result.sort((a, b) => b.rating - a.rating);
        break;
    }

    return result;
  }, [courses, filter, sortBy, searchQuery]);

  // Format helpers
  const formatCurrency = (amount: number): string => {
    return new Intl.NumberFormat('en-US', {
      style: 'currency',
      currency: 'USD',
      minimumFractionDigits: 0,
      maximumFractionDigits: 0,
    }).format(amount);
  };

  const formatNumber = (num: number): string => {
    if (num >= 1000000) return `${(num / 1000000).toFixed(1)}M`;
    if (num >= 1000) return `${(num / 1000).toFixed(1)}K`;
    return num.toString();
  };

  const formatDuration = (minutes: number): string => {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    if (hours === 0) return `${mins}m`;
    return `${hours}h ${mins}m`;
  };

  const formatTimeAgo = (date: Date): string => {
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const minutes = Math.floor(diff / 60000);
    const hours = Math.floor(diff / 3600000);
    const days = Math.floor(diff / 86400000);

    if (minutes < 60) return `${minutes}m ago`;
    if (hours < 24) return `${hours}h ago`;
    if (days < 7) return `${days}d ago`;
    return date.toLocaleDateString();
  };

  const getStatusColor = (status: CreatorCourse['status']) => {
    switch (status) {
      case 'published':
        return 'bg-green-500/20 text-green-400';
      case 'draft':
        return 'bg-yellow-500/20 text-yellow-400';
      case 'archived':
        return 'bg-gray-500/20 text-gray-400';
    }
  };

  const getActivityIcon = (type: RecentActivity['type']) => {
    switch (type) {
      case 'enrollment':
        return <UsersIcon className="w-4 h-4 text-blue-400" />;
      case 'review':
        return <StarIcon className="w-4 h-4 text-yellow-400" />;
      case 'completion':
        return <AcademicCapIcon className="w-4 h-4 text-green-400" />;
      case 'revenue':
        return <CurrencyDollarIcon className="w-4 h-4 text-emerald-400" />;
    }
  };

  return (
    <div className={`space-y-6 ${compact ? '' : ''}`}>
      {/* Header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Creator Dashboard</h1>
          <p className="text-gray-400 text-sm mt-1">Manage your courses and track performance</p>
        </div>
        <div className="flex items-center gap-3">
          {onRefresh && (
            <button
              onClick={onRefresh}
              disabled={isLoading}
              className="p-2 text-gray-400 hover:text-white hover:bg-gray-700 rounded-lg transition-colors"
            >
              <ArrowPathIcon className={`w-5 h-5 ${isLoading ? 'animate-spin' : ''}`} />
            </button>
          )}
          {onCreateCourse && (
            <button
              onClick={onCreateCourse}
              className="flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-500 transition-colors"
            >
              <PlusIcon className="w-5 h-5" />
              Create Course
            </button>
          )}
        </div>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        <div className="bg-gray-800/50 rounded-lg p-4 border border-gray-700">
          <div className="flex items-center justify-between mb-2">
            <UsersIcon className="w-8 h-8 text-blue-400" />
            <div
              className={`flex items-center gap-1 text-xs ${
                stats.studentsChange >= 0 ? 'text-green-400' : 'text-red-400'
              }`}
            >
              {stats.studentsChange >= 0 ? (
                <ArrowTrendingUpIcon className="w-3 h-3" />
              ) : (
                <ArrowTrendingDownIcon className="w-3 h-3" />
              )}
              {Math.abs(stats.studentsChange)}%
            </div>
          </div>
          <p className="text-2xl font-bold text-white">{formatNumber(stats.totalStudents)}</p>
          <p className="text-gray-400 text-sm">Total Students</p>
        </div>

        <div className="bg-gray-800/50 rounded-lg p-4 border border-gray-700">
          <div className="flex items-center justify-between mb-2">
            <CurrencyDollarIcon className="w-8 h-8 text-emerald-400" />
            <div
              className={`flex items-center gap-1 text-xs ${
                stats.revenueChange >= 0 ? 'text-green-400' : 'text-red-400'
              }`}
            >
              {stats.revenueChange >= 0 ? (
                <ArrowTrendingUpIcon className="w-3 h-3" />
              ) : (
                <ArrowTrendingDownIcon className="w-3 h-3" />
              )}
              {Math.abs(stats.revenueChange)}%
            </div>
          </div>
          <p className="text-2xl font-bold text-white">{formatCurrency(stats.totalRevenue)}</p>
          <p className="text-gray-400 text-sm">Total Revenue</p>
        </div>

        <div className="bg-gray-800/50 rounded-lg p-4 border border-gray-700">
          <div className="flex items-center justify-between mb-2">
            <AcademicCapIcon className="w-8 h-8 text-purple-400" />
          </div>
          <p className="text-2xl font-bold text-white">{stats.totalCourses}</p>
          <p className="text-gray-400 text-sm">Total Courses</p>
        </div>

        <div className="bg-gray-800/50 rounded-lg p-4 border border-gray-700">
          <div className="flex items-center justify-between mb-2">
            <StarIcon className="w-8 h-8 text-yellow-400" />
          </div>
          <p className="text-2xl font-bold text-white">{stats.avgRating.toFixed(1)}</p>
          <p className="text-gray-400 text-sm">Average Rating</p>
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Courses Section */}
        <div className="lg:col-span-2 bg-gray-800/50 rounded-lg border border-gray-700 overflow-hidden">
          {/* Filters Header */}
          <div className="p-4 border-b border-gray-700">
            <div className="flex flex-col sm:flex-row sm:items-center gap-4">
              <div className="relative flex-1">
                <MagnifyingGlassIcon className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
                <input
                  type="text"
                  value={searchQuery}
                  onChange={(e) => setSearchQuery(e.target.value)}
                  placeholder="Search courses..."
                  className="w-full bg-gray-900/50 border border-gray-700 rounded-lg pl-9 pr-4 py-2 text-sm text-white placeholder-gray-500 focus:border-blue-500 focus:outline-none"
                />
              </div>
              <div className="flex items-center gap-2">
                <select
                  value={filter}
                  onChange={(e) => setFilter(e.target.value as CourseFilter)}
                  className="bg-gray-900/50 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:border-blue-500 focus:outline-none"
                >
                  <option value="all">All Status</option>
                  <option value="published">Published</option>
                  <option value="draft">Draft</option>
                  <option value="archived">Archived</option>
                </select>
                <select
                  value={sortBy}
                  onChange={(e) => setSortBy(e.target.value as SortOption)}
                  className="bg-gray-900/50 border border-gray-700 rounded-lg px-3 py-2 text-sm text-white focus:border-blue-500 focus:outline-none"
                >
                  <option value="newest">Newest</option>
                  <option value="popular">Most Popular</option>
                  <option value="revenue">Highest Revenue</option>
                  <option value="rating">Best Rated</option>
                </select>
              </div>
            </div>
          </div>

          {/* Courses List */}
          <div className="divide-y divide-gray-700 max-h-[500px] overflow-y-auto">
            {filteredCourses.length > 0 ? (
              filteredCourses.map((course) => (
                <div
                  key={course.id}
                  className="p-4 hover:bg-gray-700/30 transition-colors"
                >
                  <div className="flex items-start gap-4">
                    {/* Thumbnail */}
                    <div className="w-24 aspect-video bg-gray-700 rounded-lg overflow-hidden flex-shrink-0">
                      {course.thumbnail ? (
                        <img
                          src={course.thumbnail}
                          alt={course.title}
                          className="w-full h-full object-cover"
                        />
                      ) : (
                        <div className="w-full h-full flex items-center justify-center">
                          <PlayCircleIcon className="w-8 h-8 text-gray-500" />
                        </div>
                      )}
                    </div>

                    {/* Info */}
                    <div className="flex-1 min-w-0">
                      <div className="flex items-start justify-between gap-2">
                        <div>
                          <h3 className="text-white font-medium truncate">{course.title}</h3>
                          <span
                            className={`inline-block mt-1 px-2 py-0.5 rounded text-xs ${getStatusColor(
                              course.status
                            )}`}
                          >
                            {course.status}
                          </span>
                        </div>
                        <div className="flex items-center gap-1">
                          {onViewCourse && (
                            <button
                              onClick={() => onViewCourse(course.id)}
                              className="p-1.5 text-gray-400 hover:text-white hover:bg-gray-700 rounded transition-colors"
                              title="View"
                            >
                              <EyeIcon className="w-4 h-4" />
                            </button>
                          )}
                          {onEditCourse && (
                            <button
                              onClick={() => onEditCourse(course.id)}
                              className="p-1.5 text-gray-400 hover:text-blue-400 hover:bg-blue-500/20 rounded transition-colors"
                              title="Edit"
                            >
                              <PencilIcon className="w-4 h-4" />
                            </button>
                          )}
                          {onDeleteCourse && (
                            <button
                              onClick={() => onDeleteCourse(course.id)}
                              className="p-1.5 text-gray-400 hover:text-red-400 hover:bg-red-500/20 rounded transition-colors"
                              title="Delete"
                            >
                              <TrashIcon className="w-4 h-4" />
                            </button>
                          )}
                        </div>
                      </div>

                      {/* Stats */}
                      <div className="flex flex-wrap items-center gap-4 mt-2 text-sm">
                        <div className="flex items-center gap-1 text-gray-400">
                          <UsersIcon className="w-4 h-4" />
                          <span>{formatNumber(course.studentsEnrolled)}</span>
                        </div>
                        <div className="flex items-center gap-1 text-gray-400">
                          <StarIcon className="w-4 h-4 text-yellow-400" />
                          <span>
                            {course.rating.toFixed(1)} ({course.reviewsCount})
                          </span>
                        </div>
                        <div className="flex items-center gap-1 text-gray-400">
                          <PlayCircleIcon className="w-4 h-4" />
                          <span>{course.lessonsCount} lessons</span>
                        </div>
                        <div className="flex items-center gap-1 text-emerald-400">
                          <CurrencyDollarIcon className="w-4 h-4" />
                          <span>{formatCurrency(course.revenue)}</span>
                        </div>
                      </div>

                      {/* Completion Rate */}
                      <div className="mt-2">
                        <div className="flex items-center justify-between text-xs mb-1">
                          <span className="text-gray-400">Completion Rate</span>
                          <span className="text-white">{course.completionRate}%</span>
                        </div>
                        <div className="h-1.5 bg-gray-700 rounded-full overflow-hidden">
                          <div
                            className="h-full bg-blue-500 rounded-full"
                            style={{ width: `${course.completionRate}%` }}
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              ))
            ) : (
              <div className="p-8 text-center">
                <AcademicCapIcon className="w-12 h-12 mx-auto text-gray-500 mb-3" />
                <p className="text-gray-400">No courses found</p>
                {onCreateCourse && (
                  <button
                    onClick={onCreateCourse}
                    className="mt-3 text-blue-400 text-sm hover:underline"
                  >
                    Create your first course
                  </button>
                )}
              </div>
            )}
          </div>
        </div>

        {/* Recent Activity */}
        <div className="bg-gray-800/50 rounded-lg border border-gray-700 overflow-hidden">
          <div className="p-4 border-b border-gray-700">
            <h2 className="text-white font-semibold">Recent Activity</h2>
          </div>
          <div className="divide-y divide-gray-700 max-h-[500px] overflow-y-auto">
            {recentActivity.length > 0 ? (
              recentActivity.map((activity) => (
                <div key={activity.id} className="p-4 hover:bg-gray-700/30 transition-colors">
                  <div className="flex items-start gap-3">
                    <div className="p-2 bg-gray-700 rounded-lg">
                      {getActivityIcon(activity.type)}
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="text-white text-sm">{activity.message}</p>
                      {activity.courseName && (
                        <p className="text-gray-400 text-xs mt-0.5 truncate">{activity.courseName}</p>
                      )}
                      <p className="text-gray-500 text-xs mt-1">
                        <ClockIcon className="w-3 h-3 inline mr-1" />
                        {formatTimeAgo(activity.timestamp)}
                      </p>
                    </div>
                  </div>
                </div>
              ))
            ) : (
              <div className="p-8 text-center">
                <ChartBarIcon className="w-12 h-12 mx-auto text-gray-500 mb-3" />
                <p className="text-gray-400 text-sm">No recent activity</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default CreatorDashboard;
