import { useState, useEffect, useRef } from 'react'
import { useParams } from 'react-router-dom'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useAuthStore } from '@/store'
import { sportEventsApi } from '@/api/sport-events'
import { TradingPanel } from '@/components/bets/TradingPanel'
import { MyOtherBets } from '@/components/bets/MyOtherBets'
import { Loading } from '@/components/common/Loading'
import { Button } from '@/components/common/Button'
import { Header } from '@/components/layout/Header'
import { MessageCircle, List, Send } from 'lucide-react'
import { useEventWebSocket } from '@/hooks/useEventWebSocket'
import { format } from 'date-fns'
import toast from 'react-hot-toast'
import type { EventComment } from '@/types/sport-event'

type TabType = 'comments' | 'mybets'

export const EventDetail = () => {
  const { id } = useParams<{ id: string }>()
  const eventId = parseInt(id || '0', 10)
  const { isAuthenticated, user } = useAuthStore()
  const queryClient = useQueryClient()
  const [activeTab, setActiveTab] = useState<TabType>('comments')
  const [newComment, setNewComment] = useState('')
  const commentsEndRef = useRef<HTMLDivElement>(null)

  const { data: event, isLoading, error } = useQuery({
    queryKey: ['sport-event', eventId, isAuthenticated],
    queryFn: () =>
      isAuthenticated
        ? sportEventsApi.getEventWithGrid(eventId)
        : sportEventsApi.getPublicEventWithGrid(eventId),
    enabled: eventId > 0,
  })

  const { data: commentsData, isLoading: isLoadingComments } = useQuery({
    queryKey: ['event-comments', eventId],
    queryFn: () => sportEventsApi.getEventComments(eventId),
    enabled: eventId > 0 && activeTab === 'comments',
  })

  const addCommentMutation = useMutation({
    mutationFn: (content: string) => sportEventsApi.addEventComment(eventId, content),
    onSuccess: () => {
      setNewComment('')
      queryClient.invalidateQueries({ queryKey: ['event-comments', eventId] })
    },
    onError: (error: any) => {
      toast.error(error.response?.data?.detail || 'Failed to add comment')
    },
  })

  // Connect to WebSocket for live updates
  useEventWebSocket({
    eventId,
    onBetCreated: (data) => {
      toast.success(`New bet: $${data.stake_amount} on ${data.team} at ${data.spread}`, {
        icon: '📈',
        duration: 3000,
      })
    },
    onBetTaken: (data) => {
      toast.success(`Bet matched: $${data.stake_amount} at ${data.spread}`, {
        icon: '🤝',
        duration: 3000,
      })
    },
    onBetCancelled: (data) => {
      toast(`Bet cancelled at ${data.spread}`, {
        icon: '❌',
        duration: 3000,
      })
    },
    onNewComment: () => {
      // Comments are automatically refetched by the WebSocket hook
    },
  })

  // Scroll to bottom when comments change
  useEffect(() => {
    if (activeTab === 'comments') {
      commentsEndRef.current?.scrollIntoView({ behavior: 'smooth' })
    }
  }, [commentsData?.comments, activeTab])

  const handleBetCreated = () => {
    queryClient.invalidateQueries({ queryKey: ['sport-event', eventId] })
    queryClient.invalidateQueries({ queryKey: ['public-sport-events'] })
  }

  const handleBetTaken = () => {
    queryClient.invalidateQueries({ queryKey: ['sport-event', eventId] })
    queryClient.invalidateQueries({ queryKey: ['public-sport-events'] })
  }

  const handleSubmitComment = (e: React.FormEvent) => {
    e.preventDefault()
    if (newComment.trim()) {
      addCommentMutation.mutate(newComment.trim())
    }
  }

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Header />
        <div className="px-4 sm:px-6 lg:px-8 py-8">
          <div className="mt-8">
            <Loading />
          </div>
        </div>
      </div>
    )
  }

  if (error || !event) {
    return (
      <div className="min-h-screen bg-gray-50">
        <Header />
        <div className="px-4 sm:px-6 lg:px-8 py-8">
          <div className="mt-8 text-center py-12 bg-white rounded-lg shadow">
            <p className="text-gray-500">Event not found</p>
          </div>
        </div>
      </div>
    )
  }

  const comments = commentsData?.comments || []

  return (
    <div className="min-h-screen bg-gray-50">
      <Header />
      <div className="px-4 sm:px-6 lg:px-8 py-8">
        {/* Trading Panel - Exchange-style interface */}
        <div className="mb-8">
          <TradingPanel
            event={event}
            onBetCreated={handleBetCreated}
            onBetTaken={handleBetTaken}
          />
        </div>

        {/* Tabbed Section - Comments / My Bets */}
        <div className="bg-white rounded-xl shadow-sm border overflow-hidden">
          {/* Tabs */}
          <div className="flex border-b">
            <button
              onClick={() => setActiveTab('comments')}
              className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 text-sm font-medium transition-colors ${
                activeTab === 'comments'
                  ? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50/50'
                  : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
              }`}
            >
              <MessageCircle size={18} />
              Comments {commentsData?.total ? `(${commentsData.total})` : ''}
            </button>
            <button
              onClick={() => setActiveTab('mybets')}
              className={`flex-1 flex items-center justify-center gap-2 px-4 py-3 text-sm font-medium transition-colors ${
                activeTab === 'mybets'
                  ? 'text-blue-600 border-b-2 border-blue-600 bg-blue-50/50'
                  : 'text-gray-500 hover:text-gray-700 hover:bg-gray-50'
              }`}
            >
              <List size={18} />
              My Bets
            </button>
          </div>

          {/* Tab Content */}
          <div className="p-0">
            {activeTab === 'comments' ? (
              <div>
                {/* Comments List */}
                <div className="h-80 overflow-y-auto p-4 space-y-4">
                  {isLoadingComments ? (
                    <div className="flex items-center justify-center py-8">
                      <Loading />
                    </div>
                  ) : comments.length === 0 ? (
                    <div className="text-center py-8 text-gray-500">
                      No comments yet. {isAuthenticated && 'Be the first to comment!'}
                    </div>
                  ) : (
                    comments.map((comment: EventComment) => {
                      const isOwnComment = user?.id === comment.user_id
                      return (
                        <div
                          key={comment.id}
                          className={`flex ${isOwnComment ? 'justify-end' : 'justify-start'}`}
                        >
                          <div
                            className={`max-w-[70%] rounded-lg p-3 ${
                              isOwnComment
                                ? 'bg-blue-500 text-white'
                                : 'bg-gray-100 text-gray-900'
                            }`}
                          >
                            <div className="flex items-center gap-2 mb-1">
                              <span className={`text-xs font-medium ${isOwnComment ? 'text-blue-100' : 'text-gray-500'}`}>
                                {comment.username}
                              </span>
                              <span className={`text-xs ${isOwnComment ? 'text-blue-200' : 'text-gray-400'}`}>
                                {format(new Date(comment.created_at), 'p')}
                              </span>
                            </div>
                            <p className="text-sm">{comment.content}</p>
                          </div>
                        </div>
                      )
                    })
                  )}
                  <div ref={commentsEndRef} />
                </div>

                {/* Comment Input */}
                {isAuthenticated ? (
                  <form onSubmit={handleSubmitComment} className="p-4 border-t bg-gray-50">
                    <div className="flex gap-2">
                      <input
                        type="text"
                        value={newComment}
                        onChange={(e) => setNewComment(e.target.value)}
                        placeholder="Type a message..."
                        maxLength={500}
                        className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                      />
                      <Button
                        type="submit"
                        disabled={!newComment.trim() || addCommentMutation.isPending}
                      >
                        <Send className="w-4 h-4" />
                      </Button>
                    </div>
                  </form>
                ) : (
                  <div className="p-4 border-t bg-gray-50 text-center text-sm text-gray-500">
                    <a href="/login" className="text-blue-600 hover:underline">Log in</a> to join the conversation
                  </div>
                )}
              </div>
            ) : (
              <div className="p-4">
                <MyOtherBets currentEventId={eventId} />
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}
