import { useState, useEffect, useRef } from "react";
import { Send, Bot, User, CheckCircle2, Loader2, AlertCircle } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { cn } from "@/lib/utils";
import { useChat } from "@/features/chat/hooks/useChat";
import { Message } from "@/features/chat/types/chat.types";

interface ChatAssistantProps {
  verificationRequest?: { fieldName: string; content: string } | null;
  onVerificationHandled?: () => void;
  readOnly?: boolean; // If true, user can only view messages (for Editor role)
}

export default function ChatAssistant({ verificationRequest, onVerificationHandled, readOnly = false }: ChatAssistantProps) {
  const [messages, setMessages] = useState<Message[]>([
    {
      id: 1,
      role: "assistant",
      content: "Xin chào! Tôi là Trợ lý Sáng kiến. Tôi có thể giúp bạn kiểm tra nội dung các mục trong đơn đăng ký sáng kiến hoặc giải đáp thắc mắc về quy trình và chính sách. Bạn cần hỗ trợ gì?",
    },
  ]);
  const [input, setInput] = useState("");
  const scrollRef = useRef<HTMLDivElement>(null);
  const { sendMessage, verifyContent, isLoading } = useChat();

  // Handle verification requests from the form
  useEffect(() => {
    if (verificationRequest) {
      const verifyMessage: Message = {
        id: Date.now(),
        role: "user",
        content: `[Kiểm tra nội dung: ${verificationRequest.fieldName}]\n\n"${verificationRequest.content}"`,
        isVerification: true,
        fieldName: verificationRequest.fieldName,
      };

      setMessages((prev) => [...prev, verifyMessage]);

      // Add loading message
      const loadingMessage: Message = {
        id: Date.now() + 1,
        role: "assistant",
        content: "Đang kiểm tra nội dung...",
        isLoading: true,
      };
      setMessages((prev) => [...prev, loadingMessage]);

      // Call real API for verification
      verifyContent(verificationRequest.fieldName, verificationRequest.content)
        .then((response) => {
          setMessages((prev) =>
            prev.map((msg) =>
              msg.id === loadingMessage.id
                ? {
                    ...msg,
                    content: response,
                    isLoading: false,
                  }
                : msg
            )
          );
          onVerificationHandled?.();
        })
        .catch((error) => {
          setMessages((prev) =>
            prev.map((msg) =>
              msg.id === loadingMessage.id
                ? {
                    ...msg,
                    content: `Xin lỗi, đã xảy ra lỗi khi kiểm tra nội dung: ${error.message || "Lỗi không xác định"}`,
                    isLoading: false,
                    error: error.message,
                  }
                : msg
            )
          );
          onVerificationHandled?.();
        });
    }
  }, [verificationRequest, onVerificationHandled, verifyContent]);

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

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

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

    const userInput = input;
    setMessages((prev) => [...prev, userMessage]);
    setInput("");

    // Add loading message
    const loadingMessage: Message = {
      id: Date.now() + 1,
      role: "assistant",
      content: "Đang suy nghĩ...",
      isLoading: true,
    };
    setMessages((prev) => [...prev, loadingMessage]);

    try {
      // Build conversation history (last 10 messages for context)
      const conversationHistory = messages
        .filter((msg) => !msg.isLoading && !msg.error)
        .slice(-10)
        .map((msg) => ({
          role: msg.role,
          content: msg.content,
        }));

      // Call real API with conversation history
      const response = await sendMessage(userInput, conversationHistory);
      
      // Update loading message with response
      setMessages((prev) =>
        prev.map((msg) =>
          msg.id === loadingMessage.id
            ? {
                ...msg,
                content: response,
                isLoading: false,
                timestamp: new Date(),
              }
            : msg
        )
      );
    } catch (error: any) {
      // Update loading message with error
      setMessages((prev) =>
        prev.map((msg) =>
          msg.id === loadingMessage.id
            ? {
                ...msg,
                content: `Xin lỗi, đã xảy ra lỗi: ${error.message || "Không thể kết nối với máy chủ"}`,
                isLoading: false,
                error: error.message,
                timestamp: new Date(),
              }
            : msg
        )
      );
    }
  };

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

  return (
    <div className="flex flex-col h-full bg-card rounded-lg border">
      {/* Header */}
      <div className="flex items-center gap-2 p-4 border-b bg-primary/5">
        <div className="p-2 rounded-full bg-primary/10">
          <Bot className="h-5 w-5 text-primary" />
        </div>
        <div>
          <h3 className="font-semibold text-sm">Trợ lý Sáng kiến</h3>
          <p className="text-xs text-muted-foreground">Hỗ trợ kiểm tra & tư vấn</p>
        </div>
      </div>

      {/* Messages */}
      <ScrollArea className="flex-1 p-4" ref={scrollRef}>
        <div className="space-y-4">
          {messages.map((message) => (
            <div
              key={message.id}
              className={cn(
                "flex gap-2",
                message.role === "user" ? "justify-end" : "justify-start"
              )}
            >
              {message.role === "assistant" && (
                <div className="p-1.5 rounded-full bg-primary/10 h-fit">
                  <Bot className="h-4 w-4 text-primary" />
                </div>
              )}
              <div
                className={cn(
                  "max-w-[85%] rounded-lg px-3 py-2 text-sm whitespace-pre-wrap",
                  message.role === "user"
                    ? message.isVerification
                      ? "bg-secondary text-secondary-foreground border border-primary/30"
                      : "bg-primary text-primary-foreground"
                    : message.error
                    ? "bg-destructive/10 text-destructive border border-destructive/20"
                    : "bg-muted"
                )}
              >
                {message.isVerification && (
                  <div className="flex items-center gap-1 text-xs text-primary mb-1">
                    <CheckCircle2 size={12} />
                    <span>Yêu cầu kiểm tra</span>
                  </div>
                )}
                {message.isLoading ? (
                  <div className="flex items-center gap-2">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    <span>{message.content}</span>
                  </div>
                ) : message.error ? (
                  <div className="flex items-center gap-2">
                    <AlertCircle className="h-4 w-4" />
                    <span>{message.content}</span>
                  </div>
                ) : (
                  message.content
                )}
              </div>
              {message.role === "user" && (
                <div className="p-1.5 rounded-full bg-secondary h-fit">
                  <User className="h-4 w-4 text-secondary-foreground" />
                </div>
              )}
            </div>
          ))}
        </div>
      </ScrollArea>

      {/* Input - Hidden for read-only mode (Editor) */}
      {!readOnly ? (
        <div className="p-4 border-t">
          <div className="flex gap-2">
            <Input
              placeholder="Nhập câu hỏi của bạn..."
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={handleKeyDown}
              className="flex-1"
            />
            <Button size="icon" onClick={handleSend} disabled={!input.trim() || isLoading}>
              {isLoading ? (
                <Loader2 className="h-4 w-4 animate-spin" />
              ) : (
                <Send className="h-4 w-4" />
              )}
            </Button>
          </div>
        </div>
      ) : (
        <div className="p-4 border-t bg-muted/50">
          <p className="text-xs text-muted-foreground text-center">
            Chế độ chỉ xem - Không thể gửi tin nhắn
          </p>
        </div>
      )}
    </div>
  );
}
