"use client"

import { useState, useRef, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card } from "@/components/ui/card"
import { Input } from "@/components/ui/input"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Send, User, Copy, RotateCcw, ThumbsUp, ThumbsDown, Paperclip, Mic, Square } from "lucide-react"
import { NovaLogo } from "@/components/ui/nova-logo"

type Message = {
  id: string
  content: string
  role: "user" | "assistant"
  timestamp: Date
  isStreaming?: boolean
}

export function AIChatInterfaceBlock() {
  const [input, setInput] = useState("")
  const [isGenerating, setIsGenerating] = useState(false)
  const [messages, setMessages] = useState<Message[]>([
    {
      id: "1",
      content:
        "Hello! I'm Nova, your AI assistant. I can help you with a wide variety of tasks like writing, analysis, math, coding, creative projects, and answering questions. What would you like to work on today?",
      role: "assistant",
      timestamp: new Date(Date.now() - 1000 * 60 * 5),
    },
    {
      id: "2",
      content:
        "Can you help me understand the key principles of responsive web design and provide some practical examples?",
      role: "user",
      timestamp: new Date(Date.now() - 1000 * 60 * 4),
    },
    {
      id: "3",
      content: `I'd be happy to explain responsive web design! Here are the key principles:

## Core Principles

**1. Fluid Grid Layouts**
Use relative units like percentages instead of fixed pixels for layout containers.

**2. Flexible Images and Media**
Ensure images scale appropriately with their containers using \`max-width: 100%\`.

**3. Media Queries**
Apply different styles based on device characteristics like screen width.

## Practical Examples

### CSS Grid Example
\`\`\`css
.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1rem;
}
\`\`\`

### Responsive Typography
\`\`\`css
h1 {
  font-size: clamp(1.5rem, 4vw, 3rem);
}
\`\`\`

### Mobile-First Media Query
\`\`\`css
/* Mobile styles first */
.sidebar { display: none; }

/* Tablet and up */
@media (min-width: 768px) {
  .sidebar { display: block; }
}
\`\`\`

These techniques ensure your website looks great on all devices, from mobile phones to desktop computers.`,
      role: "assistant",
      timestamp: new Date(Date.now() - 1000 * 60 * 3),
    },
  ])
  const scrollAreaRef = useRef<HTMLDivElement>(null)

  const handleSend = async () => {
    if (!input.trim() || isGenerating) return

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

    setMessages((prev) => [...prev, userMessage])
    setInput("")
    setIsGenerating(true)

    // Simulate AI response with streaming effect
    setTimeout(() => {
      const aiMessage: Message = {
        id: (Date.now() + 1).toString(),
        content: getAIResponse(input),
        role: "assistant",
        timestamp: new Date(),
        isStreaming: true,
      }
      setMessages((prev) => [...prev, aiMessage])

      // Stop streaming after delay
      setTimeout(() => {
        setMessages((prev) => prev.map((msg) => (msg.id === aiMessage.id ? { ...msg, isStreaming: false } : msg)))
        setIsGenerating(false)
      }, 2000)
    }, 500)
  }

  const getAIResponse = (userInput: string): string => {
    const input = userInput.toLowerCase()
    if (input.includes("hello") || input.includes("hi")) {
      return "Hello! How can I assist you today? I'm Nova, your AI companion, and I'm here to help with any questions or tasks you might have."
    } else if (input.includes("code") || input.includes("programming")) {
      return `I'd be happy to help with coding! Here's a simple example:

\`\`\`javascript
function greetUser(name) {
  return \`Hello, \${name}! Welcome to our application.\`;
}

console.log(greetUser("Developer"));
\`\`\`

What specific programming topic would you like to explore?`
    } else {
      return "That's an interesting question! I'd be happy to help you explore this topic further. Could you provide a bit more context about what specifically you'd like to know?"
    }
  }

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text)
  }

  const formatTime = (date: Date) => {
    return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
  }

  useEffect(() => {
    if (scrollAreaRef.current) {
      scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight
    }
  }, [messages])

  return (
    <Card className="w-full max-w-[800px] h-[700px] flex flex-col bg-background">
      {/* Header */}
      <div className="border-b px-6 py-4 flex items-center justify-between">
        <div className="flex items-center gap-3">
          <div className="w-8 h-8">
            <NovaLogo />
          </div>
          <div>
            <h3 className="font-semibold text-sm">Nova</h3>
            <p className="text-xs text-muted-foreground">AI Assistant</p>
          </div>
        </div>
        <Button variant="ghost" size="sm" className="text-xs">
          New Chat
        </Button>
      </div>

      {/* Messages */}
      <ScrollArea className="flex-1" ref={scrollAreaRef}>
        <div className="max-w-3xl mx-auto">
          {messages.map((message, index) => (
            <div
              key={message.id}
              className={`px-6 py-6 ${
                message.role === "assistant" ? "bg-muted/30" : "bg-background"
              } ${index !== messages.length - 1 ? "border-b" : ""}`}
            >
              <div className="flex gap-4 max-w-none">
                {/* Avatar */}
                <div className="flex-shrink-0 mt-1">
                  {message.role === "assistant" ? (
                    <div className="w-7 h-7">
                      <NovaLogo />
                    </div>
                  ) : (
                    <div className="w-7 h-7 rounded-full bg-primary flex items-center justify-center">
                      <User className="w-4 h-4 text-primary-foreground" />
                    </div>
                  )}
                </div>

                {/* Content */}
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 mb-2">
                    <span className="font-semibold text-sm">{message.role === "assistant" ? "Nova" : "You"}</span>
                    <span className="text-xs text-muted-foreground">{formatTime(message.timestamp)}</span>
                    {message.isStreaming && (
                      <div className="flex items-center gap-1 text-xs text-muted-foreground">
                        <div className="w-1 h-1 bg-current rounded-full animate-pulse" />
                        <span>Generating...</span>
                      </div>
                    )}
                  </div>

                  <div className="prose prose-sm max-w-none dark:prose-invert">
                    <div className="whitespace-pre-wrap text-sm leading-relaxed">{message.content}</div>
                  </div>

                  {/* Message Actions */}
                  {message.role === "assistant" && !message.isStreaming && (
                    <div className="flex items-center gap-1 mt-3 pt-2">
                      <Button
                        variant="ghost"
                        size="sm"
                        className="h-7 px-2 text-xs"
                        onClick={() => copyToClipboard(message.content)}
                      >
                        <Copy className="w-3 h-3 mr-1" />
                        Copy
                      </Button>
                      <Button variant="ghost" size="sm" className="h-7 px-2 text-xs">
                        <RotateCcw className="w-3 h-3 mr-1" />
                        Regenerate
                      </Button>
                      <div className="flex items-center ml-2">
                        <Button variant="ghost" size="sm" className="h-7 w-7 p-0">
                          <ThumbsUp className="w-3 h-3" />
                        </Button>
                        <Button variant="ghost" size="sm" className="h-7 w-7 p-0">
                          <ThumbsDown className="w-3 h-3" />
                        </Button>
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>
          ))}

          {/* Generating indicator */}
          {isGenerating && (
            <div className="px-6 py-6 bg-muted/30">
              <div className="flex gap-4">
                <div className="w-7 h-7">
                  <NovaLogo />
                </div>
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-2">
                    <span className="font-semibold text-sm">Nova</span>
                    <div className="flex items-center gap-1 text-xs text-muted-foreground">
                      <div className="w-1 h-1 bg-current rounded-full animate-pulse" />
                      <span>Thinking...</span>
                    </div>
                  </div>
                  <div className="flex space-x-1">
                    <div className="w-2 h-2 rounded-full bg-muted-foreground/40 animate-bounce [animation-delay:-0.3s]"></div>
                    <div className="w-2 h-2 rounded-full bg-muted-foreground/40 animate-bounce [animation-delay:-0.15s]"></div>
                    <div className="w-2 h-2 rounded-full bg-muted-foreground/40 animate-bounce"></div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </ScrollArea>

      {/* Input */}
      <div className="border-t p-4">
        <div className="max-w-3xl mx-auto">
          <form
            onSubmit={(e) => {
              e.preventDefault()
              handleSend()
            }}
            className="relative"
          >
            <div className="flex items-end gap-2 p-3 border rounded-xl bg-background focus-within:ring-2 focus-within:ring-ring">
              <Button type="button" variant="ghost" size="sm" className="h-8 w-8 p-0 flex-shrink-0">
                <Paperclip className="w-4 h-4" />
              </Button>

              <Input
                value={input}
                onChange={(e) => setInput(e.target.value)}
                placeholder="Message Nova..."
                className="flex-1 border-0 bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0 resize-none min-h-[20px] max-h-[120px]"
                disabled={isGenerating}
              />

              <div className="flex items-center gap-1 flex-shrink-0">
                <Button type="button" variant="ghost" size="sm" className="h-8 w-8 p-0">
                  <Mic className="w-4 h-4" />
                </Button>

                {isGenerating ? (
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    className="h-8 w-8 p-0"
                    onClick={() => setIsGenerating(false)}
                  >
                    <Square className="w-3 h-3" />
                  </Button>
                ) : (
                  <Button type="submit" size="sm" className="h-8 w-8 p-0" disabled={!input.trim()}>
                    <Send className="w-4 h-4" />
                  </Button>
                )}
              </div>
            </div>
          </form>

          <p className="text-xs text-muted-foreground text-center mt-2">
            Nova can make mistakes. Please use with discretion.
          </p>
        </div>
      </div>
    </Card>
  )
}
