'use client'

import { useState, useEffect, useRef } from 'react'
import { useSession } from 'next-auth/react'
import { trpc } from '@/lib/trpc/client'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Skeleton } from '@/components/ui/skeleton'
import { Avatar, AvatarFallback } from '@/components/ui/avatar'
import { Send, MessageSquare } from 'lucide-react'
import { toast } from 'sonner'
import { formatDistanceToNow } from 'date-fns'

interface WorkspaceChatProps {
  mentorAssignmentId: string
}

export function WorkspaceChat({ mentorAssignmentId }: WorkspaceChatProps) {
  const { data: session } = useSession()
  const [message, setMessage] = useState('')
  const messagesEndRef = useRef<HTMLDivElement>(null)
  const utils = trpc.useUtils()

  const { data: messages, isLoading } = trpc.mentor.workspaceGetMessages.useQuery(
    { mentorAssignmentId },
    {
      enabled: !!mentorAssignmentId,
      refetchInterval: 10000, // Poll every 10 seconds
    }
  )

  const sendMutation = trpc.mentor.workspaceSendMessage.useMutation({
    onSuccess: () => {
      utils.mentor.workspaceGetMessages.invalidate({ mentorAssignmentId })
      setMessage('')
      toast.success('Message sent')
    },
    onError: (err) => toast.error(err.message),
  })

  const handleSend = () => {
    if (!message.trim()) return
    sendMutation.mutate({
      mentorAssignmentId,
      message: message,
      role: 'MENTOR_ROLE',
    })
  }

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSend()
    }
  }

  // Auto-scroll to bottom
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [messages])

  if (isLoading) {
    return (
      <Card>
        <CardHeader>
          <Skeleton className="h-6 w-48" />
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {[1, 2, 3].map((i) => (
              <Skeleton key={i} className="h-16" />
            ))}
          </div>
        </CardContent>
      </Card>
    )
  }

  const currentUserId = session?.user?.id

  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <MessageSquare className="h-5 w-5" />
          Workspace Chat
        </CardTitle>
        <CardDescription>
          Communicate with the project team
        </CardDescription>
      </CardHeader>
      <CardContent className="space-y-4">
        {/* Messages list */}
        <div className="h-[400px] overflow-y-auto space-y-3 p-4 border rounded-lg bg-muted/20">
          {!messages || messages.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-full text-center">
              <MessageSquare className="h-12 w-12 text-muted-foreground/50 mb-3" />
              <p className="text-sm text-muted-foreground">No messages yet</p>
              <p className="text-xs text-muted-foreground mt-1">
                Start the conversation by sending a message below
              </p>
            </div>
          ) : (
            <>
              {messages.map((msg: any) => {
                const isMe = msg.senderId === currentUserId
                const isMentor = msg.sender?.role === 'MENTOR'

                return (
                  <div
                    key={msg.id}
                    className={`flex gap-3 ${isMe ? 'flex-row-reverse' : 'flex-row'}`}
                  >
                    <Avatar className="h-8 w-8 shrink-0">
                      <AvatarFallback
                        className={
                          isMentor
                            ? 'bg-brand-teal text-white'
                            : 'bg-brand-blue text-white'
                        }
                      >
                        {msg.sender?.name?.charAt(0).toUpperCase() || '?'}
                      </AvatarFallback>
                    </Avatar>
                    <div className={`flex-1 min-w-0 ${isMe ? 'items-end' : 'items-start'} flex flex-col`}>
                      <div
                        className={`rounded-lg px-4 py-2 max-w-[80%] ${
                          isMe
                            ? 'bg-brand-blue text-white'
                            : isMentor
                            ? 'bg-brand-teal/10 border border-brand-teal/20'
                            : 'bg-white border'
                        }`}
                      >
                        <p className="text-sm font-medium mb-1">
                          {msg.sender?.name || 'Unknown'}
                          {isMentor && !isMe && (
                            <span className="ml-2 text-xs opacity-75">(Mentor)</span>
                          )}
                        </p>
                        <p className={`text-sm ${isMe ? 'text-white' : 'text-foreground'}`}>
                          {msg.content}
                        </p>
                        <p className={`text-xs mt-1 ${isMe ? 'text-white/70' : 'text-muted-foreground'}`}>
                          {msg.createdAt && formatDistanceToNow(new Date(msg.createdAt), { addSuffix: true })}
                        </p>
                      </div>
                    </div>
                  </div>
                )
              })}
              <div ref={messagesEndRef} />
            </>
          )}
        </div>

        {/* Input area */}
        <div className="flex gap-2">
          <Textarea
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            onKeyDown={handleKeyPress}
            placeholder="Type your message... (Press Enter to send, Shift+Enter for new line)"
            className="flex-1 resize-none"
            rows={3}
          />
          <Button
            onClick={handleSend}
            disabled={!message.trim() || sendMutation.isPending}
            className="shrink-0 bg-brand-blue hover:bg-brand-blue-light"
          >
            <Send className="h-4 w-4" />
          </Button>
        </div>
      </CardContent>
    </Card>
  )
}
