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

export default function PostMenu({ post, currentUser, onClose, onDelete }) {
  const [showReportModal, setShowReportModal] = useState(false)
  const [reportReason, setReportReason] = useState('')
  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 (
      <div className="report-modal-overlay" 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>
    )
  }

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

  return (
    <div className="post-menu-overlay" onClick={handleOverlayClick}>
      <div className="menu-header" onClick={(e) => e.stopPropagation()}>
        <button className="menu-close-btn" onClick={onClose}>
          <X size={24} />
        </button>
        <h2>Действия</h2>
        <div style={{ width: 40 }} />
      </div>

      <div className="menu-items" onClick={(e) => e.stopPropagation()}>
        {isOwnPost || isModerator ? (
          <button className="menu-item danger" onClick={onDelete}>
            <Trash2 size={20} />
            <span>Удалить пост</span>
          </button>
        ) : (
          <button className="menu-item" onClick={() => setShowReportModal(true)}>
            <Flag size={20} />
            <span>Пожаловаться</span>
          </button>
        )}
        
        <button className="menu-item" onClick={onClose}>
          <X size={20} />
          <span>Отмена</span>
        </button>
      </div>
    </div>
  )
}

