use axum::{
    extract::{Path, State},
    response::Html,
    routing::get,
    Router,
};
use std::sync::Arc;
use uuid::Uuid;

use crate::shared::state::AppState;

pub async fn handle_learn_list_page(State(_state): State<Arc<AppState>>) -> Html<String> {
    let html = r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Learning Center</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; }
        .container { max-width: 1400px; margin: 0 auto; padding: 24px; }
        .header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px; }
        .header h1 { font-size: 28px; color: #1a1a1a; }
        .btn { padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500; }
        .btn-primary { background: #0066cc; color: white; }
        .btn-primary:hover { background: #0052a3; }
        .stats-row { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-bottom: 24px; }
        .stat-card { background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
        .stat-value { font-size: 28px; font-weight: 600; color: #0066cc; }
        .stat-label { font-size: 13px; color: #666; margin-top: 4px; }
        .tabs { display: flex; gap: 4px; margin-bottom: 24px; border-bottom: 1px solid #e0e0e0; }
        .tab { padding: 12px 24px; background: none; border: none; cursor: pointer; font-size: 14px; color: #666; border-bottom: 2px solid transparent; }
        .tab.active { color: #0066cc; border-bottom-color: #0066cc; }
        .course-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 24px; }
        .course-card { background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.08); cursor: pointer; transition: transform 0.2s, box-shadow 0.2s; }
        .course-card:hover { transform: translateY(-2px); box-shadow: 0 4px 16px rgba(0,0,0,0.12); }
        .course-thumbnail { width: 100%; aspect-ratio: 16/9; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); position: relative; }
        .course-thumbnail img { width: 100%; height: 100%; object-fit: cover; }
        .course-badge { position: absolute; top: 12px; left: 12px; padding: 4px 10px; background: rgba(0,0,0,0.7); color: white; border-radius: 4px; font-size: 11px; font-weight: 500; }
        .course-progress-bar { position: absolute; bottom: 0; left: 0; right: 0; height: 4px; background: rgba(255,255,255,0.3); }
        .course-progress-fill { height: 100%; background: #4caf50; }
        .course-info { padding: 16px; }
        .course-title { font-size: 16px; font-weight: 600; color: #1a1a1a; margin-bottom: 8px; }
        .course-meta { font-size: 13px; color: #666; display: flex; gap: 12px; margin-bottom: 12px; }
        .course-description { font-size: 14px; color: #666; line-height: 1.5; }
        .course-footer { display: flex; justify-content: space-between; align-items: center; margin-top: 12px; padding-top: 12px; border-top: 1px solid #f0f0f0; }
        .course-author { font-size: 13px; color: #666; }
        .course-rating { display: flex; align-items: center; gap: 4px; font-size: 13px; }
        .filters { display: flex; gap: 12px; margin-bottom: 24px; }
        .search-box { flex: 1; padding: 10px 16px; border: 1px solid #ddd; border-radius: 8px; }
        .filter-select { padding: 8px 16px; border: 1px solid #ddd; border-radius: 8px; background: white; }
        .empty-state { text-align: center; padding: 80px 24px; color: #666; }
        .empty-state h3 { margin-bottom: 8px; color: #1a1a1a; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Learning Center</h1>
            <button class="btn btn-primary" onclick="createCourse()">Create Course</button>
        </div>
        <div class="stats-row">
            <div class="stat-card">
                <div class="stat-value" id="coursesInProgress">0</div>
                <div class="stat-label">Courses In Progress</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="coursesCompleted">0</div>
                <div class="stat-label">Completed</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="totalHours">0h</div>
                <div class="stat-label">Learning Hours</div>
            </div>
            <div class="stat-card">
                <div class="stat-value" id="certificates">0</div>
                <div class="stat-label">Certificates Earned</div>
            </div>
        </div>
        <div class="tabs">
            <button class="tab active" data-view="all">All Courses</button>
            <button class="tab" data-view="my-courses">My Courses</button>
            <button class="tab" data-view="in-progress">In Progress</button>
            <button class="tab" data-view="completed">Completed</button>
            <button class="tab" data-view="bookmarked">Bookmarked</button>
        </div>
        <div class="filters">
            <input type="text" class="search-box" placeholder="Search courses..." id="searchInput">
            <select class="filter-select" id="categoryFilter">
                <option value="">All Categories</option>
                <option value="development">Development</option>
                <option value="business">Business</option>
                <option value="design">Design</option>
                <option value="marketing">Marketing</option>
                <option value="compliance">Compliance</option>
            </select>
            <select class="filter-select" id="levelFilter">
                <option value="">All Levels</option>
                <option value="beginner">Beginner</option>
                <option value="intermediate">Intermediate</option>
                <option value="advanced">Advanced</option>
            </select>
            <select class="filter-select" id="sortBy">
                <option value="popular">Most Popular</option>
                <option value="newest">Newest</option>
                <option value="rating">Highest Rated</option>
            </select>
        </div>
        <div class="course-grid" id="courseGrid">
            <div class="empty-state">
                <h3>No courses available</h3>
                <p>Check back later for new learning content</p>
            </div>
        </div>
    </div>
    <script>
        let currentView = 'all';

        document.querySelectorAll('.tab').forEach(tab => {
            tab.addEventListener('click', () => {
                document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                tab.classList.add('active');
                currentView = tab.dataset.view;
                loadCourses();
            });
        });

        async function loadCourses() {
            try {
                const response = await fetch('/api/learn/courses');
                const courses = await response.json();
                renderCourses(courses);
                updateStats(courses);
            } catch (e) {
                console.error('Failed to load courses:', e);
            }
        }

        function renderCourses(courses) {
            const grid = document.getElementById('courseGrid');
            if (!courses || courses.length === 0) {
                grid.innerHTML = '<div class="empty-state"><h3>No courses available</h3><p>Check back later for new learning content</p></div>';
                return;
            }

            grid.innerHTML = courses.map(c => `
                <div class="course-card" onclick="window.location='/suite/learn/${c.id}'">
                    <div class="course-thumbnail" style="${c.thumbnail_url ? '' : 'background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);'}">
                        ${c.thumbnail_url ? `<img src="${c.thumbnail_url}" alt="${c.title}">` : ''}
                        <span class="course-badge">${c.category || 'General'}</span>
                        ${c.progress !== undefined ? `<div class="course-progress-bar"><div class="course-progress-fill" style="width: ${c.progress}%"></div></div>` : ''}
                    </div>
                    <div class="course-info">
                        <div class="course-title">${c.title}</div>
                        <div class="course-meta">
                            <span>📚 ${c.lessons_count || 0} lessons</span>
                            <span>⏱️ ${c.duration || '0h'}</span>
                            <span>📊 ${c.level || 'All levels'}</span>
                        </div>
                        <div class="course-description">${truncate(c.description || '', 100)}</div>
                        <div class="course-footer">
                            <span class="course-author">by ${c.author || 'Unknown'}</span>
                            <span class="course-rating">⭐ ${c.rating || '0.0'} (${c.reviews_count || 0})</span>
                        </div>
                    </div>
                </div>
            `).join('');
        }

        function truncate(str, len) {
            return str.length > len ? str.substring(0, len) + '...' : str;
        }

        function updateStats(courses) {
            const inProgress = courses.filter(c => c.progress > 0 && c.progress < 100).length;
            const completed = courses.filter(c => c.progress === 100).length;
            document.getElementById('coursesInProgress').textContent = inProgress;
            document.getElementById('coursesCompleted').textContent = completed;
        }

        function createCourse() {
            window.location = '/suite/learn/create';
        }

        loadCourses();
    </script>
</body>
</html>"#;
    Html(html.to_string())
}

pub async fn handle_learn_course_page(
    State(_state): State<Arc<AppState>>,
    Path(course_id): Path<Uuid>,
) -> Html<String> {
    let html = format!(r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Course</title>
    <style>
        * {{ box-sizing: border-box; margin: 0; padding: 0; }}
        body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; }}
        .container {{ max-width: 1200px; margin: 0 auto; padding: 24px; }}
        .back-link {{ color: #0066cc; text-decoration: none; display: inline-block; margin-bottom: 16px; }}
        .course-header {{ background: white; border-radius: 12px; padding: 32px; margin-bottom: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }}
        .course-title {{ font-size: 28px; font-weight: 600; margin-bottom: 16px; }}
        .course-meta {{ display: flex; gap: 24px; color: #666; margin-bottom: 16px; }}
        .course-description {{ line-height: 1.6; color: #444; margin-bottom: 20px; }}
        .progress-section {{ background: #f9f9f9; border-radius: 8px; padding: 16px; }}
        .progress-bar {{ height: 8px; background: #e0e0e0; border-radius: 4px; overflow: hidden; margin-top: 8px; }}
        .progress-fill {{ height: 100%; background: #4caf50; transition: width 0.3s; }}
        .content-grid {{ display: grid; grid-template-columns: 2fr 1fr; gap: 24px; }}
        .lessons-section {{ background: white; border-radius: 12px; padding: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }}
        .section-title {{ font-size: 18px; font-weight: 600; margin-bottom: 16px; }}
        .lesson-item {{ display: flex; align-items: center; gap: 16px; padding: 16px; border: 1px solid #e0e0e0; border-radius: 8px; margin-bottom: 12px; cursor: pointer; transition: background 0.15s; }}
        .lesson-item:hover {{ background: #f8f9fa; }}
        .lesson-item.completed {{ background: #e8f5e9; border-color: #c8e6c9; }}
        .lesson-item.current {{ background: #e3f2fd; border-color: #90caf9; }}
        .lesson-number {{ width: 32px; height: 32px; border-radius: 50%; background: #e0e0e0; display: flex; align-items: center; justify-content: center; font-weight: 600; font-size: 14px; flex-shrink: 0; }}
        .lesson-item.completed .lesson-number {{ background: #4caf50; color: white; }}
        .lesson-item.current .lesson-number {{ background: #2196f3; color: white; }}
        .lesson-info {{ flex: 1; }}
        .lesson-title {{ font-weight: 500; margin-bottom: 4px; }}
        .lesson-meta {{ font-size: 13px; color: #666; }}
        .sidebar-card {{ background: white; border-radius: 12px; padding: 20px; margin-bottom: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }}
        .btn {{ padding: 12px 24px; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500; width: 100%; }}
        .btn-primary {{ background: #0066cc; color: white; }}
        .btn-primary:hover {{ background: #0052a3; }}
        .instructor {{ display: flex; align-items: center; gap: 12px; }}
        .instructor-avatar {{ width: 48px; height: 48px; border-radius: 50%; background: #e0e0e0; }}
        .instructor-name {{ font-weight: 600; }}
        .instructor-title {{ font-size: 13px; color: #666; }}
    </style>
</head>
<body>
    <div class="container">
        <a href="/suite/learn" class="back-link">← Back to Courses</a>
        <div class="course-header">
            <h1 class="course-title" id="courseTitle">Loading...</h1>
            <div class="course-meta">
                <span id="courseLessons">0 lessons</span>
                <span id="courseDuration">0h</span>
                <span id="courseLevel">All levels</span>
                <span id="courseRating">⭐ 0.0</span>
            </div>
            <p class="course-description" id="courseDescription"></p>
            <div class="progress-section">
                <strong>Your Progress: <span id="progressPercent">0%</span></strong>
                <div class="progress-bar"><div class="progress-fill" id="progressFill" style="width: 0%"></div></div>
            </div>
        </div>
        <div class="content-grid">
            <div class="lessons-section">
                <h2 class="section-title">Course Content</h2>
                <div id="lessonsList"></div>
            </div>
            <div class="sidebar">
                <div class="sidebar-card">
                    <button class="btn btn-primary" id="continueBtn" onclick="continueLearning()">Start Learning</button>
                </div>
                <div class="sidebar-card">
                    <h3 class="section-title">Instructor</h3>
                    <div class="instructor">
                        <div class="instructor-avatar"></div>
                        <div>
                            <div class="instructor-name" id="instructorName">Loading...</div>
                            <div class="instructor-title" id="instructorTitle"></div>
                        </div>
                    </div>
                </div>
                <div class="sidebar-card">
                    <h3 class="section-title">What You'll Learn</h3>
                    <ul id="learningObjectives" style="padding-left: 20px; color: #444; line-height: 1.8;"></ul>
                </div>
            </div>
        </div>
    </div>
    <script>
        const courseId = '{course_id}';
        let currentLessonIndex = 0;

        async function loadCourse() {{
            try {{
                const response = await fetch(`/api/learn/courses/${{courseId}}`);
                const course = await response.json();
                if (course) {{
                    document.getElementById('courseTitle').textContent = course.title;
                    document.getElementById('courseDescription').textContent = course.description || '';
                    document.getElementById('courseLessons').textContent = `${{course.lessons_count || 0}} lessons`;
                    document.getElementById('courseDuration').textContent = course.duration || '0h';
                    document.getElementById('courseLevel').textContent = course.level || 'All levels';
                    document.getElementById('courseRating').textContent = `⭐ ${{course.rating || '0.0'}}`;
                    document.getElementById('instructorName').textContent = course.author || 'Unknown';

                    const progress = course.progress || 0;
                    document.getElementById('progressPercent').textContent = progress + '%';
                    document.getElementById('progressFill').style.width = progress + '%';
                    document.getElementById('continueBtn').textContent = progress > 0 ? 'Continue Learning' : 'Start Learning';

                    if (course.lessons && course.lessons.length > 0) {{
                        renderLessons(course.lessons);
                    }}

                    if (course.objectives && course.objectives.length > 0) {{
                        document.getElementById('learningObjectives').innerHTML = course.objectives.map(o => `<li>${{o}}</li>`).join('');
                    }}
                }}
            }} catch (e) {{
                console.error('Failed to load course:', e);
            }}
        }}

        function renderLessons(lessons) {{
            const list = document.getElementById('lessonsList');
            list.innerHTML = lessons.map((l, i) => `
                <div class="lesson-item ${{l.completed ? 'completed' : ''}} ${{l.current ? 'current' : ''}}" onclick="openLesson('${{l.id}}')">
                    <div class="lesson-number">${{l.completed ? '✓' : i + 1}}</div>
                    <div class="lesson-info">
                        <div class="lesson-title">${{l.title}}</div>
                        <div class="lesson-meta">${{l.type || 'Video'}} • ${{l.duration || '5 min'}}</div>
                    </div>
                </div>
            `).join('');
        }}

        function openLesson(lessonId) {{
            window.location = `/suite/learn/${{courseId}}/lesson/${{lessonId}}`;
        }}

        function continueLearning() {{
            window.location = `/suite/learn/${{courseId}}/lesson/next`;
        }}

        loadCourse();
    </script>
</body>
</html>"#);
    Html(html)
}

pub async fn handle_learn_create_page(State(_state): State<Arc<AppState>>) -> Html<String> {
    let html = r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Course</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; }
        .container { max-width: 800px; margin: 0 auto; padding: 24px; }
        .back-link { color: #0066cc; text-decoration: none; display: inline-block; margin-bottom: 16px; }
        .form-card { background: white; border-radius: 12px; padding: 32px; box-shadow: 0 2px 8px rgba(0,0,0,0.08); }
        h1 { font-size: 24px; margin-bottom: 24px; }
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; font-weight: 500; margin-bottom: 8px; }
        .form-group input, .form-group textarea, .form-group select { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 14px; }
        .form-group textarea { min-height: 120px; resize: vertical; }
        .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        .btn { padding: 12px 24px; border: none; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: 500; }
        .btn-primary { background: #0066cc; color: white; }
        .btn-primary:hover { background: #0052a3; }
        .btn-secondary { background: #f5f5f5; color: #333; }
        .form-actions { display: flex; gap: 12px; justify-content: flex-end; }
    </style>
</head>
<body>
    <div class="container">
        <a href="/suite/learn" class="back-link">← Back to Courses</a>
        <div class="form-card">
            <h1>Create New Course</h1>
            <form id="courseForm">
                <div class="form-group">
                    <label>Course Title</label>
                    <input type="text" id="title" required placeholder="Enter course title">
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea id="description" placeholder="Describe what students will learn"></textarea>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>Category</label>
                        <select id="category">
                            <option value="development">Development</option>
                            <option value="business">Business</option>
                            <option value="design">Design</option>
                            <option value="marketing">Marketing</option>
                            <option value="compliance">Compliance</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Level</label>
                        <select id="level">
                            <option value="beginner">Beginner</option>
                            <option value="intermediate">Intermediate</option>
                            <option value="advanced">Advanced</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <label>Learning Objectives (one per line)</label>
                    <textarea id="objectives" placeholder="What will students learn?"></textarea>
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="window.location='/suite/learn'">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Course</button>
                </div>
            </form>
        </div>
    </div>
    <script>
        document.getElementById('courseForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const data = {
                title: document.getElementById('title').value,
                description: document.getElementById('description').value,
                category: document.getElementById('category').value,
                level: document.getElementById('level').value,
                objectives: document.getElementById('objectives').value.split('\n').filter(o => o.trim())
            };

            try {
                const response = await fetch('/api/learn/courses', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    const course = await response.json();
                    window.location = `/suite/learn/${course.id}`;
                } else {
                    alert('Failed to create course');
                }
            } catch (e) {
                alert('Error: ' + e.message);
            }
        });
    </script>
</body>
</html>"#;
    Html(html.to_string())
}

pub fn configure_learn_ui_routes() -> Router<Arc<AppState>> {
    Router::new()
        .route("/suite/learn", get(handle_learn_list_page))
        .route("/suite/learn/create", get(handle_learn_create_page))
        .route("/suite/learn/:id", get(handle_learn_course_page))
}
