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) {
    return (
      <div className="report-modal-overlay">
        <div className="report-modal-header">
          <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">
          <textarea
            placeholder="Опишите причину жалобы..."
            value={reportReason}
            onChange={e => setReportReason(e.target.value)}
            maxLength={500}
            autoFocus
          />
        </div>
      </div>
    )
  }

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

      <div className="menu-items">
        {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>
  )
}

