'use client'

import { useState, useEffect, useRef } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { ScrollArea } from '@/components/ui/scroll-area'
import { X, Send } from 'lucide-react'

interface ChatMessage {
  id: string
  from: 'technician' | 'agent'
  text: string
  timestamp: Date
}

interface ChatPanelProps {
  onClose: () => void
  sendEvent: (event: Record<string, unknown>) => void
  incomingMessage: Record<string, unknown> | null
}

export function ChatPanel({ onClose, sendEvent, incomingMessage }: ChatPanelProps) {
  const [messages, setMessages] = useState<ChatMessage[]>([])
  const [input, setInput] = useState('')
  const scrollRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    if (!incomingMessage) return
    if (incomingMessage.type === 'chat_message') {
      setMessages(prev => [...prev, {
        id: crypto.randomUUID(),
        from: 'agent',
        text: incomingMessage.text as string,
        timestamp: new Date(),
      }])
    }
  }, [incomingMessage])

  useEffect(() => {
    // Auto-scroll to bottom on new messages
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight
    }
  }, [messages])

  const send = () => {
    const text = input.trim()
    if (!text) return
    sendEvent({ type: 'chat_message', text })
    setMessages(prev => [...prev, {
      id: crypto.randomUUID(),
      from: 'technician',
      text,
      timestamp: new Date(),
    }])
    setInput('')
  }

  const fmt = (d: Date) =>
    d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })

  return (
    <div className="w-72 border-l border-border/50 bg-card flex flex-col h-full">
      <div className="flex items-center justify-between p-3 border-b border-border/50">
        <span className="text-sm font-medium">Session Chat</span>
        <Button variant="ghost" size="icon" className="h-6 w-6" onClick={onClose}>
          <X className="h-3.5 w-3.5" />
        </Button>
      </div>

      <div ref={scrollRef} className="flex-1 overflow-y-auto p-3 space-y-3">
        {messages.length === 0 && (
          <p className="text-xs text-muted-foreground text-center pt-8">
            Messages sent here are forwarded to the remote machine.
          </p>
        )}
        {messages.map((m) => (
          <div key={m.id} className={`flex flex-col gap-0.5 ${m.from === 'technician' ? 'items-end' : 'items-start'}`}>
            <div className={`max-w-[85%] rounded-lg px-3 py-1.5 text-xs ${
              m.from === 'technician'
                ? 'bg-primary text-primary-foreground'
                : 'bg-muted text-foreground'
            }`}>
              {m.text}
            </div>
            <span className="text-[10px] text-muted-foreground">{fmt(m.timestamp)}</span>
          </div>
        ))}
      </div>

      <div className="p-2 border-t border-border/50 flex gap-1.5">
        <Input
          value={input}
          onChange={e => setInput(e.target.value)}
          onKeyDown={e => { if (e.key === 'Enter') send() }}
          placeholder="Type a message…"
          className="h-8 text-xs"
        />
        <Button size="icon" className="h-8 w-8 shrink-0" onClick={send} disabled={!input.trim()}>
          <Send className="h-3.5 w-3.5" />
        </Button>
      </div>
    </div>
  )
}
