import { X, Trash2, AlertCircle, Flag, Edit2 } from 'lucide-react'
import { useState } from 'react'
import { createPortal } from 'react-dom'
import { reportPost, editPost } from '../utils/api'
import { hapticFeedback, showConfirm } from '../utils/telegram'
import './PostMenu.css'

export default function PostMenu({ post, currentUser, onClose, onDelete, onUpdate, buttonPosition }) {
  const [showReportModal, setShowReportModal] = useState(false)
  const [showEditModal, setShowEditModal] = useState(false)
  const [reportReason, setReportReason] = useState('')
  const [editContent, setEditContent] = useState(post.content || '')
  const [submitting, setSubmitting] = useState(false)

  const isOwnPost = post.author._id === currentUser.id
  const isModerator = currentUser.role === 'moderator' || currentUser.role === 'admin'

  const handleReport = async () => {
    if (!reportReason.trim()) {
      alert('Укажите причину жалобы')
      return
    }

    try {
      setSubmitting(true)
      hapticFeedback('light')
      await reportPost(post._id, reportReason)
      hapticFeedback('success')
      alert('Жалоба отправлена')
      onClose()
    } catch (error) {
      console.error('Ошибка отправки жалобы:', error)
      hapticFeedback('error')
      alert('Ошибка отправки жалобы')
    } finally {
      setSubmitting(false)
    }
  }

  if (showReportModal) {
    const handleReportOverlayClick = (e) => {
      if (e.target === e.currentTarget) {
        setShowReportModal(false)
      }
    }

    return createPortal(
      <div 
        className="report-modal-overlay"
        onMouseDown={(e) => e.stopPropagation()}
        onTouchStart={(e) => e.stopPropagation()}
        onClick={handleReportOverlayClick}
      >
        <div className="report-modal-header" onClick={(e) => e.stopPropagation()}>
          <button className="menu-close-btn" onClick={onClose}>
            <X size={24} />
          </button>
          <h2>Пожаловаться</h2>
          <button
            className="submit-btn"
            onClick={handleReport}
            disabled={submitting || !reportReason.trim()}
          >
            {submitting ? 'Отправка...' : 'Отправить'}
          </button>
        </div>

        <div className="report-modal-body" onClick={(e) => e.stopPropagation()}>
          <textarea
            placeholder="Опишите причину жалобы..."
            value={reportReason}
            onChange={e => setReportReason(e.target.value)}
            maxLength={500}
            autoFocus
          />
        </div>
      </div>,
      document.body
    )
  }

  const handleEdit = async () => {
    if (!editContent.trim()) {
      alert('Текст поста не может быть пустым')
      return
    }

    try {
      setSubmitting(true)
      hapticFeedback('light')
      await editPost(post._id, { content: editContent })
      hapticFeedback('success')
      setShowEditModal(false)
      onClose()
      if (onUpdate) {
        onUpdate()
      }
    } catch (error) {
      console.error('Ошибка редактирования поста:', error)
      hapticFeedback('error')
      alert('Ошибка редактирования поста')
    } finally {
      setSubmitting(false)
    }
  }

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

  if (showEditModal) {
    return createPortal(
      <div 
        className="post-menu-overlay"
        onMouseDown={(e) => e.stopPropagation()}
        onTouchStart={(e) => e.stopPropagation()}
        onClick={handleOverlayClick}
      >
        <div className="edit-menu-content" onClick={(e) => e.stopPropagation()}>
          <div className="edit-menu-header">
            <h3>Редактировать пост</h3>
            <button className="menu-close-btn" onClick={() => setShowEditModal(false)}>
              <X size={18} />
            </button>
          </div>
          <textarea
            className="edit-content-input"
            value={editContent}
            onChange={e => setEditContent(e.target.value)}
            placeholder="Текст поста..."
            maxLength={2000}
            rows={6}
            autoFocus
          />
          <div className="edit-menu-actions">
            <button
              className="edit-cancel-btn"
              onClick={() => {
                setShowEditModal(false)
                setEditContent(post.content || '')
              }}
            >
              Отмена
            </button>
            <button
              className="edit-save-btn"
              onClick={handleEdit}
              disabled={submitting || !editContent.trim()}
            >
              {submitting ? 'Сохранение...' : 'Сохранить'}
            </button>
          </div>
        </div>
      </div>,
      document.body
    )
  }

  const getMenuStyle = () => {
    if (!buttonPosition) return {}
    
    const menuWidth = 160 // Примерная ширина меню
    const padding = 16 // Отступ от края экрана
    const buttonCenterX = buttonPosition.left + (buttonPosition.right - buttonPosition.left) / 2
    const windowWidth = window.innerWidth
    
    let left = buttonCenterX
    let transform = 'translateX(-50%)'
    
    // Проверка правого края
    if (buttonCenterX + menuWidth / 2 > windowWidth - padding) {
      left = windowWidth - padding - menuWidth / 2
      transform = 'translateX(-50%)'
    }
    
    // Проверка левого края
    if (buttonCenterX - menuWidth / 2 < padding) {
      left = padding + menuWidth / 2
      transform = 'translateX(-50%)'
    }
    
    return {
      position: 'fixed',
      top: `${buttonPosition.bottom + 4}px`,
      left: `${left}px`,
      transform: transform,
      width: 'auto',
      minWidth: '140px',
      maxWidth: `${windowWidth - padding * 2}px`
    }
  }

  return createPortal(
    <div 
      className="post-menu-overlay"
      onMouseDown={(e) => e.stopPropagation()}
      onTouchStart={(e) => e.stopPropagation()}
      onClick={handleOverlayClick}
    >
      <div className="menu-content" style={getMenuStyle()} onClick={(e) => e.stopPropagation()}>
        <div className="menu-items" onClick={(e) => e.stopPropagation()}>
          {(isOwnPost || isModerator) && (
            <>
              {isOwnPost && (
                <button className="menu-item" onClick={() => setShowEditModal(true)}>
                  <Edit2 size={18} />
                  <span>Редактировать</span>
                </button>
              )}
              <button className="menu-item danger" onClick={onDelete}>
                <Trash2 size={18} />
                <span>Удалить</span>
              </button>
            </>
          )}
          {!isOwnPost && (
            <button className="menu-item" onClick={() => setShowReportModal(true)}>
              <Flag size={18} />
              <span>Пожаловаться</span>
            </button>
          )}
        </div>
      </div>
    </div>,
    document.body
  )
}

