import React, { useState, useRef, useEffect } from "react";
import { ChatMessage } from "../services/types";
import { chatStream } from "../services/gemini";

const ChatView: React.FC = () => {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState("");
  const [isTyping, setIsTyping] = useState(false);
  const scrollRef = useRef<HTMLDivElement>(null);

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

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

    const userMsg: ChatMessage = {
      role: "user",
      text: input,
      timestamp: new Date(),
    };
    setMessages((prev) => [...prev, userMsg]);
    setInput("");
    setIsTyping(true);

    let modelResponse = "";
    const modelMsg: ChatMessage = {
      role: "model",
      text: "",
      timestamp: new Date(),
    };
    setMessages((prev) => [...prev, modelMsg]);

    try {
      await chatStream([...messages, userMsg], (chunk) => {
        modelResponse += chunk;
        setMessages((prev) => {
          const updated = [...prev];
          updated[updated.length - 1] = {
            ...updated[updated.length - 1],
            text: modelResponse,
          };
          return updated;
        });
      });
    } catch (error) {
      console.error(error);
      setMessages((prev) => {
        const updated = [...prev];
        updated[updated.length - 1] = {
          ...updated[updated.length - 1],
          text: "Connectivity Error: Unable to reach the processing unit.",
        };
        return updated;
      });
    } finally {
      setIsTyping(false);
    }
  };

  return (
    <div className="flex flex-col h-full bg-slate-50/50">
      <div ref={scrollRef} className="flex-1 overflow-y-auto p-10 space-y-8">
        {messages.length === 0 && (
          <div className="h-full flex flex-col items-center justify-center text-center space-y-6">
            <div className="w-20 h-20 bg-white rounded-3xl flex items-center justify-center shadow-2xl border border-slate-100">
              <svg
                className="w-10 h-10 text-[#004ea8]"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z"
                />
              </svg>
            </div>
            <div>
              <h2 className="text-3xl font-black text-slate-900 tracking-tight">
                Enterprise Intelligence
              </h2>
              <p className="text-slate-500 max-w-md mt-3 text-lg">
                Sophisticated AI assistant for your professional workflow. Ask
                anything from market analysis to complex coding solutions.
              </p>
            </div>
          </div>
        )}

        {messages.map((msg, idx) => (
          <div
            key={idx}
            className={`flex ${
              msg.role === "user" ? "justify-end" : "justify-start"
            } animate-in fade-in slide-in-from-bottom-2`}
          >
            <div
              className={`max-w-[75%] rounded-3xl px-6 py-4 shadow-sm border ${
                msg.role === "user"
                  ? "bg-[#004ea8] text-white border-[#003d82] rounded-br-none shadow-blue-200 shadow-lg"
                  : "bg-white text-slate-700 border-slate-100 rounded-bl-none shadow-md"
              }`}
            >
              <p className="text-base leading-relaxed whitespace-pre-wrap font-medium">
                {msg.text}
              </p>
              <div
                className={`text-[10px] mt-3 font-bold uppercase tracking-widest ${
                  msg.role === "user" ? "text-blue-100" : "text-[#004ea8]"
                }`}
              >
                {msg.timestamp.toLocaleTimeString([], {
                  hour: "2-digit",
                  minute: "2-digit",
                })}
              </div>
            </div>
          </div>
        ))}

        {isTyping && (
          <div className="flex justify-start">
            <div className="bg-white border border-slate-100 rounded-3xl px-6 py-4 rounded-bl-none shadow-sm">
              <div className="flex space-x-2">
                <div className="w-2.5 h-2.5 bg-[#004ea8] rounded-full animate-bounce" />
                <div className="w-2.5 h-2.5 bg-[#004ea8] rounded-full animate-bounce [animation-delay:-0.15s]" />
                <div className="w-2.5 h-2.5 bg-[#004ea8] rounded-full animate-bounce [animation-delay:-0.3s]" />
              </div>
            </div>
          </div>
        )}
      </div>

      <div className="p-8 bg-white border-t border-slate-200">
        <div className="max-w-5xl mx-auto relative">
          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && handleSend()}
            placeholder="Input your query here..."
            className="w-full bg-slate-50 text-slate-900 rounded-2xl px-8 py-5 focus:outline-none focus:ring-4 focus:ring-blue-100 border border-slate-200 placeholder-slate-400 text-lg shadow-inner transition-all"
          />
          <button
            disabled={isTyping}
            onClick={handleSend}
            className="absolute right-3 top-3 bottom-3 bg-[#004ea8] hover:bg-[#003d82] disabled:bg-slate-300 text-white rounded-xl px-8 transition-all font-bold shadow-lg flex items-center space-x-2 active:scale-95"
          >
            <span>Execute</span>
            <svg
              className="w-5 h-5"
              fill="none"
              stroke="currentColor"
              viewBox="0 0 24 24"
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeWidth={2}
                d="M13 5l7 7-7 7M5 5l7 7-7 7"
              />
            </svg>
          </button>
        </div>
      </div>
    </div>
  );
};

export default ChatView;
