import { useState, useEffect, useRef } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { useAuth } from '../context/AuthContext'
import api from '../api/client'

export default function CoursesPage() {
  const { user } = useAuth()
  const isModerator = user?.role === 'admin' || user?.role === 'moderator'
  const [tab, setTab] = useState('browse')
  const [courses, setCourses] = useState([])
  const [total, setTotal] = useState(0)
  const [myCourses, setMyCourses] = useState([])
  const [createdCourses, setCreatedCourses] = useState([])
  const [loading, setLoading] = useState(true)
  const [searchQuery, setSearchQuery] = useState('')
  const [deletingId, setDeletingId] = useState(null)
  const [showCreateForm, setShowCreateForm] = useState(false)
  const [newTitle, setNewTitle] = useState('')
  const [newDescription, setNewDescription] = useState('')
  const [creating, setCreating] = useState(false)
  const navigate = useNavigate()
  const debounceRef = useRef(null)
  const LIMIT = 12

  const loadPublished = (off = 0, q = searchQuery) => {
    setLoading(true)
    const params = { limit: LIMIT, offset: off }
    if (q.trim()) params.q = q.trim()
    api.get('/courses/published', { params }).then(res => {
      if (off === 0) setCourses(res.data.courses)
      else setCourses(prev => [...prev, ...res.data.courses])
      setTotal(res.data.total)
    }).catch(() => {}).finally(() => setLoading(false))
  }

  const loadMyCourses = () => {
    setLoading(true)
    api.get('/courses/my-courses').then(res => {
      setMyCourses(res.data)
    }).catch(() => {}).finally(() => setLoading(false))
  }

  const loadCreated = () => {
    setLoading(true)
    api.get('/courses/').then(res => {
      setCreatedCourses(res.data)
    }).catch(() => {}).finally(() => setLoading(false))
  }

  useEffect(() => {
    if (tab === 'browse') loadPublished(0)
    if (tab === 'enrolled') loadMyCourses()
    if (tab === 'created') loadCreated()
  }, [tab])

  useEffect(() => {
    if (tab !== 'browse') return
    clearTimeout(debounceRef.current)
    debounceRef.current = setTimeout(() => loadPublished(0, searchQuery), 300)
    return () => clearTimeout(debounceRef.current)
  }, [searchQuery])

  const enroll = async (courseId) => {
    try {
      await api.post(`/courses/${courseId}/enroll`)
      setCourses(prev => prev.map(c => c.id === courseId ? { ...c, is_enrolled: true, enrolled_count: (c.enrolled_count || 0) + 1 } : c))
    } catch { }
  }

  const unenroll = async (courseId) => {
    try {
      await api.delete(`/courses/${courseId}/enroll`)
      setMyCourses(prev => prev.filter(c => c.id !== courseId))
    } catch { }
  }

  const togglePublish = async (courseId, currentlyPublished) => {
    try {
      const action = currentlyPublished ? 'unpublish' : 'publish'
      await api.post(`/courses/${courseId}/${action}`)
      setCreatedCourses(prev => prev.map(c => c.id === courseId ? { ...c, status: currentlyPublished ? 'draft' : 'published' } : c))
    } catch { }
  }

  const deleteCourse = async (courseId) => {
    try {
      await api.delete(`/courses/${courseId}`)
      setCreatedCourses(prev => prev.filter(c => c.id !== courseId))
      setDeletingId(null)
    } catch { }
  }

  const createCourse = async () => {
    if (!newTitle.trim()) return
    setCreating(true)
    try {
      const res = await api.post('/courses/', { title: newTitle.trim(), description: newDescription.trim() })
      setCreatedCourses(prev => [res.data, ...prev])
      setNewTitle('')
      setNewDescription('')
      setShowCreateForm(false)
    } catch { }
    finally { setCreating(false) }
  }

  if (loading && courses.length === 0 && myCourses.length === 0 && createdCourses.length === 0) {
    return <div className="loading"><div className="spinner" /></div>
  }

  return (
    <div>
      <div className="card" style={{ marginBottom: 16 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 8 }}>
          <h2 style={{ marginBottom: 0 }}>Courses</h2>
          <div style={{ display: 'flex', gap: 4 }}>
            <button className={`btn btn-sm ${tab === 'browse' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setTab('browse')}>Browse</button>
            <button className={`btn btn-sm ${tab === 'enrolled' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setTab('enrolled')}>Enrolled</button>
            {isModerator && <button className={`btn btn-sm ${tab === 'created' ? 'btn-primary' : 'btn-secondary'}`} onClick={() => setTab('created')}>Created by Me</button>}
          </div>
        </div>
      </div>

      {/* BROWSE COURSES TAB */}
      {tab === 'browse' && (
        <>
          <div style={{ marginBottom: 12 }}>
            <input type="text" placeholder="Search courses by title..." value={searchQuery} onChange={e => setSearchQuery(e.target.value)}
              style={{ width: '100%', padding: '9px 13px', border: '1px solid var(--border)', borderRadius: 8, fontSize: '0.9rem', background: 'var(--input-bg)', color: 'var(--text)' }} />
          </div>

          <p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginBottom: 12 }}>{total} course{total !== 1 ? 's' : ''}</p>

          {courses.length === 0 && !loading && (
            <div className="card"><div className="empty-state">No courses found.</div></div>
          )}

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))', gap: 12 }}>
            {courses.map(course => (
              <div key={course.id} className="card" style={{ padding: 0, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
                {course.thumbnail_path && (
                  <img src={course.thumbnail_path} alt="" style={{ width: '100%', height: 140, objectFit: 'cover' }} />
                )}
                <div style={{ padding: '16px 20px', display: 'flex', flexDirection: 'column', gap: 8, flex: 1 }}>
                <h3 style={{ fontSize: '1rem', marginBottom: 0 }}>{course.title}</h3>
                {course.description && (
                  <p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginBottom: 0, lineHeight: 1.5 }}>
                    {course.description.length > 120 ? course.description.slice(0, 120) + '...' : course.description}
                  </p>
                )}
                <div style={{ fontSize: '0.82rem', color: 'var(--text-muted)', marginTop: 'auto' }}>
                  by {course.creator_name || 'Unknown'} &middot; {course.module_count || 0} module{(course.module_count || 0) !== 1 ? 's' : ''} &middot; {course.enrolled_count || 0} enrolled
                </div>
                <div style={{ display: 'flex', gap: 8, marginTop: 4 }}>
                  {course.is_enrolled ? (
                    <>
                      <button className="btn btn-primary btn-sm" onClick={() => navigate(`/courses/${course.id}`)}>Start</button>
                      <button className="btn btn-secondary btn-sm" onClick={async () => {
                        try { await api.delete(`/courses/${course.id}/enroll`); setCourses(prev => prev.map(c => c.id === course.id ? { ...c, is_enrolled: false, enrolled_count: Math.max(0, (c.enrolled_count || 1) - 1) } : c)) } catch {}
                      }}>Unenroll</button>
                    </>
                  ) : (
                    <button className="btn btn-primary btn-sm" onClick={() => enroll(course.id)}>Enroll</button>
                  )}
                </div>
                </div>
              </div>
            ))}
          </div>

          {courses.length < total && (
            <div style={{ textAlign: 'center', marginTop: 16 }}>
              <button className="btn btn-secondary" onClick={() => loadPublished(courses.length, searchQuery)} disabled={loading}>
                {loading ? 'Loading...' : `Load more (${total - courses.length} remaining)`}
              </button>
            </div>
          )}
        </>
      )}

      {/* MY COURSES (ENROLLED) TAB */}
      {tab === 'enrolled' && (
        <>
          {myCourses.length === 0 && !loading && (
            <div className="card"><div className="empty-state">You have not enrolled in any courses yet. Browse courses to get started.</div></div>
          )}

          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {myCourses.map(course => (
              <div key={course.id} className="card" style={{ padding: '16px 20px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 10 }}>
                  <div style={{ flex: 1, minWidth: 200, cursor: 'pointer' }} onClick={() => navigate(`/courses/${course.id}`)}>
                    <h3 style={{ fontSize: '1rem', marginBottom: 4 }}>{course.title}</h3>
                    {course.description && (
                      <p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginBottom: 8, lineHeight: 1.5 }}>
                        {course.description.length > 200 ? course.description.slice(0, 200) + '...' : course.description}
                      </p>
                    )}
                    <div style={{ fontSize: '0.82rem', color: 'var(--text-muted)', marginBottom: 8 }}>
                      {course.module_count || 0} module{(course.module_count || 0) !== 1 ? 's' : ''} &middot; by {course.creator_name || 'Unknown'}
                    </div>
                    <div className="progress-bar" style={{ height: 6, borderRadius: 3, background: 'var(--border)', overflow: 'hidden' }}>
                      <div className="fill" style={{ width: `${course.progress_pct || 0}%`, height: '100%', background: 'var(--primary)', borderRadius: 3, transition: 'width 0.3s' }} />
                    </div>
                    <div style={{ fontSize: '0.78rem', color: 'var(--text-muted)', marginTop: 4 }}>
                      {course.progress_pct || 0}% complete
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: 8, flexShrink: 0, alignItems: 'flex-start' }}>
                    <button className="btn btn-primary btn-sm" onClick={() => navigate(`/courses/${course.id}`)}>Continue</button>
                    <button className="btn btn-secondary btn-sm" onClick={() => unenroll(course.id)}>Unenroll</button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </>
      )}

      {/* MY CREATED TAB */}
      {tab === 'created' && (
        <>
          <div style={{ marginBottom: 12 }}>
            <button className="btn btn-primary btn-sm" onClick={() => setShowCreateForm(v => !v)}>
              {showCreateForm ? 'Cancel' : '+ Create Course'}
            </button>
          </div>

          {showCreateForm && (
            <div className="card" style={{ marginBottom: 16, padding: 20 }}>
              <h3 style={{ fontSize: '1rem', marginBottom: 12 }}>New Course</h3>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                <input type="text" placeholder="Course title..." value={newTitle} onChange={e => setNewTitle(e.target.value)}
                  onKeyDown={e => e.key === 'Enter' && createCourse()}
                  style={{ padding: '9px 13px', border: '1px solid var(--border)', borderRadius: 8, fontSize: '0.9rem', background: 'var(--input-bg)', color: 'var(--text)' }} />
                <textarea placeholder="Description (optional)..." value={newDescription} onChange={e => setNewDescription(e.target.value)}
                  rows={3}
                  style={{ padding: '9px 13px', border: '1px solid var(--border)', borderRadius: 8, fontSize: '0.9rem', background: 'var(--input-bg)', color: 'var(--text)', resize: 'vertical' }} />
                <div style={{ display: 'flex', gap: 8 }}>
                  <button className="btn btn-primary btn-sm" onClick={createCourse} disabled={creating || !newTitle.trim()}>
                    {creating ? 'Creating...' : 'Create'}
                  </button>
                  <button className="btn btn-secondary btn-sm" onClick={() => { setShowCreateForm(false); setNewTitle(''); setNewDescription('') }}>Cancel</button>
                </div>
              </div>
            </div>
          )}

          {createdCourses.length === 0 && !loading && !showCreateForm && (
            <div className="card"><div className="empty-state">You have not created any courses yet.</div></div>
          )}

          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {createdCourses.map(course => (
              <div key={course.id} className="card" style={{ padding: '16px 20px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 10 }}>
                  <div style={{ flex: 1, minWidth: 200 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                      <h3 style={{ fontSize: '1rem', marginBottom: 0 }}>{course.title}</h3>
                      <span style={{
                        fontSize: '0.72rem', padding: '2px 8px', borderRadius: 10, fontWeight: 600,
                        background: course.status === 'published' ? '#d1fae5' : '#fef3c7',
                        color: course.status === 'published' ? '#065f46' : '#92400e',
                      }}>
                        {course.status === 'published' ? 'Published' : 'Draft'}
                      </span>
                    </div>
                    {course.description && (
                      <p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', marginBottom: 4, lineHeight: 1.5 }}>
                        {course.description.length > 200 ? course.description.slice(0, 200) + '...' : course.description}
                      </p>
                    )}
                    <div style={{ fontSize: '0.82rem', color: 'var(--text-muted)' }}>
                      {course.module_count || 0} module{(course.module_count || 0) !== 1 ? 's' : ''} &middot; {course.enrolled_count || 0} enrolled &middot; {new Date(course.created_at).toLocaleDateString()}
                    </div>
                  </div>
                  <div style={{ display: 'flex', gap: 6, flexShrink: 0, alignItems: 'flex-start' }}>
                    <button className="btn btn-secondary btn-sm" onClick={() => navigate(`/courses/${course.id}/edit`)}>Edit</button>
                    <button className="btn btn-secondary btn-sm" onClick={() => togglePublish(course.id, course.status === 'published')}>
                      {course.status === 'published' ? 'Unpublish' : 'Publish'}
                    </button>
                    {deletingId === course.id ? (
                      <div style={{ display: 'flex', gap: 4 }}>
                        <button className="btn btn-danger btn-sm" onClick={() => deleteCourse(course.id)}>Yes, delete</button>
                        <button className="btn btn-secondary btn-sm" onClick={() => setDeletingId(null)}>Cancel</button>
                      </div>
                    ) : (
                      <button className="btn btn-danger btn-sm" onClick={() => setDeletingId(course.id)}>Delete</button>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </>
      )}
    </div>
  )
}
