"use client"

import React, { useState, useRef, useEffect } from "react"
import { chartService } from "../../services/api"
import "../../styles/chat.css"

interface Message {
  id: string
  type: "user" | "assistant"
  content: string
  timestamp: Date
}

export const ChatInterface = () => {
  const [image, setImage] = useState<File | null>(null)
  const [preview, setPreview] = useState<string | null>(null)
  const [messages, setMessages] = useState<Message[]>([])
  const [inputMessage, setInputMessage] = useState("")
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState("")
  const [conversationId, setConversationId] = useState<string | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const messagesEndRef = useRef<HTMLDivElement>(null)

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
  }

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files && e.target.files[0]) {
      const file = e.target.files[0]
      setImage(file)
      setMessages([]) // Clear conversation when new image is uploaded
      setConversationId(null)

      const reader = new FileReader()
      reader.onloadend = () => {
        setPreview(reader.result as string)
      }
      reader.readAsDataURL(file)
    }
  }

  const handleSendMessage = async (e: React.FormEvent) => {
    e.preventDefault()

    if (!inputMessage.trim() || !image) return

    const userMessage: Message = {
      id: Date.now().toString(),
      type: "user",
      content: inputMessage,
      timestamp: new Date()
    }

    setMessages(prev => [...prev, userMessage])
    setInputMessage("")
    setIsLoading(true)
    setError("")

    try {
      const formData = new FormData()
      formData.append("image", image)
      formData.append("question", inputMessage)

      const response = await chartService.AskQuestion(formData)
      
      const assistantMessage: Message = {
        id: (Date.now() + 1).toString(),
        type: "assistant",
        content: response.data.answer,
        timestamp: new Date()
      }

      setMessages(prev => [...prev, assistantMessage])
    } catch (err: any) {
      setError(err.response?.data?.detail || "Failed to get response")
      console.error("Error in chat:", err)
    } finally {
      setIsLoading(false)
    }
  }

  const triggerFileInput = () => {
    fileInputRef.current?.click()
  }

  return (
    <div className="chat-container">
      <div className="chat-header">
        <h1>Interactive Chart Chat</h1>
        <p>Have a conversation with AI about your chart</p>
      </div>

      <div className="chat-layout">
        {/* Image Upload Section */}
        <div className="image-section">
          <input 
            type="file" 
            ref={fileInputRef} 
            onChange={handleImageChange} 
            accept="image/*" 
            className="file-input" 
          />

          {preview ? (
            <div className="image-preview-container">
              <img src={preview} alt="Chart preview" className="image-preview" />
              <button onClick={triggerFileInput} className="change-image-button">
                Change Image
              </button>
            </div>
          ) : (
            <div className="upload-area" onClick={triggerFileInput}>
              <div className="upload-icon">📊</div>
              <p>Upload a chart to start chatting</p>
              <p className="upload-hint">Supports PNG, JPG, SVG files</p>
            </div>
          )}
        </div>

        {/* Chat Messages Section */}
        <div className="chat-messages-section">
          <div className="messages-container">
            {messages.length === 0 && image && (
              <div className="welcome-message">
                <p>👋 Hi! I can help you analyze this chart. Ask me anything about it!</p>
              </div>
            )}

            {messages.map((message) => (
              <div 
                key={message.id} 
                className={`message ${message.type === "user" ? "user-message" : "assistant-message"}`}
              >
                <div className="message-content">
                  {message.content}
                </div>
                <div className="message-timestamp">
                  {message.timestamp.toLocaleTimeString()}
                </div>
              </div>
            ))}

            {isLoading && (
              <div className="message assistant-message">
                <div className="message-content">
                  <div className="typing-indicator">
                    <span></span>
                    <span></span>
                    <span></span>
                  </div>
                </div>
              </div>
            )}

            {error && (
              <div className="error-message">
                {error}
              </div>
            )}

            <div ref={messagesEndRef} />
          </div>

          {/* Message Input */}
          <form onSubmit={handleSendMessage} className="message-input-form">
            <input
              type="text"
              value={inputMessage}
              onChange={(e) => setInputMessage(e.target.value)}
              placeholder="Ask a question about your chart..."
              disabled={isLoading || !image}
              className="message-input"
            />
            <button 
              type="submit" 
              disabled={isLoading || !image || !inputMessage.trim()}
              className="send-button"
            >
              {isLoading ? "..." : "Send"}
            </button>
          </form>
        </div>
      </div>
    </div>
  )
} 