import { useState, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { X, Send } from 'lucide-react'
import { commentPost, getPosts } from '../utils/api'
import { hapticFeedback } from '../utils/telegram'
import { decodeHtmlEntities } from '../utils/htmlEntities'
import './CommentsModal.css'

export default function CommentsModal({ post, onClose, onUpdate }) {
  const [comment, setComment] = useState('')
  const [loading, setLoading] = useState(false)
  const [comments, setComments] = useState([])
  const [fullPost, setFullPost] = useState(post)
  const [loadingPost, setLoadingPost] = useState(false)
  
  // Загрузить полные данные поста с комментариями
  useEffect(() => {
    if (post?._id) {
      loadFullPost()
    } else {
      setFullPost(post)
      setComments(post?.comments || [])
    }
  }, [post?._id])
  
  const loadFullPost = async () => {
    try {
      setLoadingPost(true)
      const response = await getPosts()
      const foundPost = response.posts?.find(p => p._id === post._id)
      if (foundPost) {
        setFullPost(foundPost)
        setComments(foundPost.comments || [])
      } else {
        // Fallback на переданный post
        setFullPost(post)
        setComments(post?.comments || [])
      }
    } catch (error) {
      console.error('[CommentsModal] Ошибка загрузки поста:', error)
      // Fallback на переданный post
      setFullPost(post)
      setComments(post?.comments || [])
    } finally {
      setLoadingPost(false)
    }
  }
  
  // Проверка на существование поста
  if (!post) {
    console.error('[CommentsModal] Post is missing')
    return null
  }
  
  const displayPost = fullPost || post

  const handleSubmit = async () => {
    if (!comment.trim()) return

    try {
      setLoading(true)
      hapticFeedback('light')
      
      const result = await commentPost(post._id, comment)
      setComments(result.comments || [])
      setComment('')
      hapticFeedback('success')
      // Обновить полный пост
      await loadFullPost()
      onUpdate()
    } catch (error) {
      console.error('Ошибка добавления комментария:', error)
      hapticFeedback('error')
    } finally {
      setLoading(false)
    }
  }

  const formatDate = (date) => {
    const d = new Date(date)
    const now = new Date()
    const diff = Math.floor((now - d) / 1000) // секунды

    if (diff < 60) return 'только что'
    if (diff < 3600) return `${Math.floor(diff / 60)} мин`
    if (diff < 86400) return `${Math.floor(diff / 3600)} ч`
    
    return d.toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' })
  }

  const handleOverlayClick = (e) => {
    // Закрывать только при клике на overlay, не на контент
    if (e.target === e.currentTarget) {
      onClose()
    }
  }

  if (!post) {
    return null
  }

  return createPortal(
    <div 
      className="comments-modal-overlay" 
      onMouseDown={(e) => e.stopPropagation()}
      onTouchStart={(e) => e.stopPropagation()}
      onClick={handleOverlayClick}
    >
      <div className="comments-modal" onClick={(e) => e.stopPropagation()}>
        {/* Хедер */}
        <div className="modal-header">
          <button className="close-btn" onClick={onClose}>
            <X size={24} />
          </button>
          <h2>Комментарии</h2>
          <div style={{ width: 40 }} />
        </div>

        {/* Пост */}
        {loadingPost ? (
          <div className="post-preview">
            <div className="loading-state">
              <div className="spinner" />
              <p>Загрузка...</p>
            </div>
          </div>
        ) : (
          <div className="post-preview">
            <div className="preview-author">
              <img 
                src={displayPost.author?.photoUrl || '/default-avatar.png'} 
                alt={displayPost.author?.username || displayPost.author?.firstName || 'User'}
                className="preview-avatar"
                onError={(e) => { e.target.src = '/default-avatar.png' }}
              />
              <div>
                <div className="preview-name">
                  {displayPost.author?.firstName || ''} {displayPost.author?.lastName || ''}
                  {!displayPost.author?.firstName && !displayPost.author?.lastName && 'Пользователь'}
                </div>
                <div className="preview-username">@{displayPost.author?.username || displayPost.author?.firstName || 'user'}</div>
              </div>
            </div>
            
            {displayPost.content && (
              <div className="preview-content">{decodeHtmlEntities(displayPost.content)}</div>
            )}
            
            {((displayPost.images && displayPost.images.length > 0) || displayPost.imageUrl) && (
              <div className="preview-image">
                <img src={displayPost.images?.[0] || displayPost.imageUrl} alt="Post" />
              </div>
            )}
          </div>
        )}

        {/* Список комментариев */}
        <div className="comments-list">
          {comments.length === 0 ? (
            <div className="empty-comments">
              <p>Пока нет комментариев</p>
              <span>Будьте первым!</span>
            </div>
          ) : (
            comments
              .filter(c => c.author) // Фильтруем комментарии без автора
              .map((c, index) => (
              <div key={index} className="comment-item fade-in">
                <img
                  src={c.author?.photoUrl || '/default-avatar.png'}
                  alt={c.author?.username || c.author?.firstName || 'User'}
                  className="comment-avatar"
                  onError={(e) => { e.target.src = '/default-avatar.png' }}
                />
                <div className="comment-content">
                  <div className="comment-header">
                    <span className="comment-author">
                      {c.author?.firstName || ''} {c.author?.lastName || ''}
                      {!c.author?.firstName && !c.author?.lastName && 'Пользователь'}
                    </span>
                    <span className="comment-time">{formatDate(c.createdAt)}</span>
                  </div>
                  <p className="comment-text">{decodeHtmlEntities(c.content)}</p>
                </div>
              </div>
            ))
          )}
        </div>

        {/* Форма добавления комментария */}
        <div className="comment-form">
          <input
            type="text"
            placeholder="Написать комментарий..."
            value={comment}
            onChange={e => setComment(e.target.value)}
            onKeyPress={e => e.key === 'Enter' && handleSubmit()}
            maxLength={500}
          />
          <button
            onClick={handleSubmit}
            disabled={loading || !comment.trim()}
            className="send-btn"
          >
            <Send size={20} />
          </button>
        </div>
      </div>
    </div>
  )
}

