import { useState, useEffect, useCallback } from 'react'
import { commentsApi, usersApi, Comment, UserSearchResult } from '../services/collaboration'
import { useAuth } from '../contexts/AuthContext'

interface CommentsProps {
  taskId: string
}

export function Comments({ taskId }: CommentsProps) {
  const { user } = useAuth()
  const [comments, setComments] = useState<Comment[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [newComment, setNewComment] = useState('')
  const [submitting, setSubmitting] = useState(false)
  const [replyTo, setReplyTo] = useState<string | null>(null)
  const [editingId, setEditingId] = useState<string | null>(null)
  const [editContent, setEditContent] = useState('')
  const [mentionSuggestions, setMentionSuggestions] = useState<UserSearchResult[]>([])
  const [showMentions, setShowMentions] = useState(false)

  const fetchComments = useCallback(async () => {
    try {
      setLoading(true)
      const response = await commentsApi.list(taskId)
      setComments(response.comments)
      setError(null)
    } catch (err) {
      setError('Failed to load comments')
    } finally {
      setLoading(false)
    }
  }, [taskId])

  useEffect(() => {
    fetchComments()
  }, [fetchComments])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!newComment.trim() || submitting) return

    try {
      setSubmitting(true)
      const comment = await commentsApi.create(taskId, newComment, replyTo || undefined)
      if (replyTo) {
        // For replies, we'd need to refresh or update the parent
        await fetchComments()
      } else {
        setComments(prev => [...prev, comment])
      }
      setNewComment('')
      setReplyTo(null)
    } catch (err) {
      setError('Failed to post comment')
    } finally {
      setSubmitting(false)
    }
  }

  const handleEdit = async (commentId: string) => {
    if (!editContent.trim()) return
    try {
      const updated = await commentsApi.update(commentId, editContent)
      setComments(prev => prev.map(c => (c.id === commentId ? updated : c)))
      setEditingId(null)
      setEditContent('')
    } catch (err) {
      setError('Failed to update comment')
    }
  }

  const handleDelete = async (commentId: string) => {
    if (!confirm('Delete this comment?')) return
    try {
      await commentsApi.delete(commentId)
      await fetchComments()
    } catch (err) {
      setError('Failed to delete comment')
    }
  }

  const handleMentionSearch = async (query: string) => {
    if (query.length < 1) {
      setMentionSuggestions([])
      setShowMentions(false)
      return
    }
    try {
      const results = await usersApi.search(query)
      setMentionSuggestions(results)
      setShowMentions(results.length > 0)
    } catch {
      setMentionSuggestions([])
    }
  }

  const handleInputChange = (value: string) => {
    setNewComment(value)
    // Check for @mention
    const atMatch = value.match(/@(\w*)$/)
    if (atMatch) {
      handleMentionSearch(atMatch[1])
    } else {
      setShowMentions(false)
    }
  }

  const insertMention = (userResult: UserSearchResult) => {
    const newValue = newComment.replace(/@\w*$/, `@${userResult.name} `)
    setNewComment(newValue)
    setShowMentions(false)
  }

  if (loading) return <div className="p-4 text-gray-500">Loading comments...</div>

  return (
    <div className="space-y-4">
      <h3 className="font-semibold text-lg">Comments ({comments.length})</h3>

      {error && (
        <div className="p-2 bg-red-100 text-red-700 rounded text-sm">{error}</div>
      )}

      {/* Comment list */}
      <div className="space-y-3">
        {comments.map(comment => (
          <div key={comment.id} className="border rounded-lg p-3 bg-gray-50">
            <div className="flex justify-between items-start mb-2">
              <div>
                <span className="font-medium">{comment.author.name}</span>
                <span className="text-gray-500 text-sm ml-2">
                  {new Date(comment.created_at).toLocaleString()}
                </span>
                {comment.is_edited && (
                  <span className="text-gray-400 text-xs ml-1">(edited)</span>
                )}
              </div>
              {user?.id === comment.author.id && !comment.is_deleted && (
                <div className="flex gap-2">
                  <button
                    onClick={() => {
                      setEditingId(comment.id)
                      setEditContent(comment.content)
                    }}
                    className="text-sm text-blue-600 hover:underline"
                  >
                    Edit
                  </button>
                  <button
                    onClick={() => handleDelete(comment.id)}
                    className="text-sm text-red-600 hover:underline"
                  >
                    Delete
                  </button>
                </div>
              )}
            </div>

            {editingId === comment.id ? (
              <div className="space-y-2">
                <textarea
                  value={editContent}
                  onChange={e => setEditContent(e.target.value)}
                  className="w-full p-2 border rounded"
                  rows={2}
                />
                <div className="flex gap-2">
                  <button
                    onClick={() => handleEdit(comment.id)}
                    className="px-3 py-1 bg-blue-600 text-white rounded text-sm"
                  >
                    Save
                  </button>
                  <button
                    onClick={() => setEditingId(null)}
                    className="px-3 py-1 bg-gray-300 rounded text-sm"
                  >
                    Cancel
                  </button>
                </div>
              </div>
            ) : (
              <p className={`whitespace-pre-wrap ${comment.is_deleted ? 'text-gray-400 italic' : ''}`}>
                {comment.content}
              </p>
            )}

            {/* Mentions */}
            {comment.mentions.length > 0 && (
              <div className="mt-2 text-sm text-gray-500">
                Mentioned: {comment.mentions.map(m => m.name).join(', ')}
              </div>
            )}

            {/* Reply button */}
            {!comment.is_deleted && (
              <button
                onClick={() => setReplyTo(comment.id)}
                className="text-sm text-blue-600 hover:underline mt-2"
              >
                Reply {comment.reply_count > 0 && `(${comment.reply_count})`}
              </button>
            )}
          </div>
        ))}
      </div>

      {/* New comment form */}
      <form onSubmit={handleSubmit} className="space-y-2">
        {replyTo && (
          <div className="flex items-center gap-2 text-sm text-gray-600">
            <span>Replying to comment</span>
            <button
              type="button"
              onClick={() => setReplyTo(null)}
              className="text-red-600 hover:underline"
            >
              Cancel
            </button>
          </div>
        )}
        <div className="relative">
          <textarea
            value={newComment}
            onChange={e => handleInputChange(e.target.value)}
            placeholder="Add a comment... Use @name to mention someone"
            className="w-full p-3 border rounded-lg resize-none"
            rows={3}
          />
          {/* Mention suggestions dropdown */}
          {showMentions && (
            <div className="absolute bottom-full left-0 w-full bg-white border rounded shadow-lg max-h-40 overflow-y-auto">
              {mentionSuggestions.map(u => (
                <button
                  key={u.id}
                  type="button"
                  onClick={() => insertMention(u)}
                  className="w-full text-left px-3 py-2 hover:bg-gray-100"
                >
                  <span className="font-medium">{u.name}</span>
                  <span className="text-gray-500 text-sm ml-2">{u.email}</span>
                </button>
              ))}
            </div>
          )}
        </div>
        <button
          type="submit"
          disabled={!newComment.trim() || submitting}
          className="px-4 py-2 bg-blue-600 text-white rounded disabled:opacity-50"
        >
          {submitting ? 'Posting...' : 'Post Comment'}
        </button>
      </form>
    </div>
  )
}
