"use client";

import { useChat } from "@ai-sdk/react";
import { useState, useRef, useEffect } from "react";

const SUGGESTED_QUESTIONS = [
  "What services do you offer?",
  "How much does a website cost?",
  "How long does a project take?",
  "Can you build a mobile app?",
];

export default function Chatbot() {
  const [isOpen, setIsOpen] = useState(false);
  const [inputValue, setInputValue] = useState("");
  const [hasInteracted, setHasInteracted] = useState(false);
  const { messages, sendMessage, status } = useChat();
  const isLoading = status === "submitted" || status === "streaming";
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [messages, isOpen]);

  useEffect(() => {
    if (isOpen && inputRef.current) {
      setTimeout(() => inputRef.current?.focus(), 300);
    }
  }, [isOpen]);

  const handleFormSubmit = (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    const text = inputValue.trim();
    if (!text || isLoading) return;
    setHasInteracted(true);
    sendMessage({ text });
    setInputValue("");
  };

  const handleSuggestion = (question: string) => {
    setHasInteracted(true);
    sendMessage({ text: question });
  };

  const formatTime = () => {
    return new Date().toLocaleTimeString("en-US", {
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  return (
    <>
      {/* Floating Button */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        aria-label="Toggle chat"
        style={{
          position: "fixed",
          bottom: "28px",
          right: "28px",
          width: "60px",
          height: "60px",
          borderRadius: "50%",
          background: isOpen
            ? "#1e293b"
            : "linear-gradient(135deg, #16a34a 0%, #15803d 100%)",
          border: "none",
          cursor: "pointer",
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          zIndex: 9999,
          boxShadow: "0 8px 32px rgba(22,163,74,0.35), 0 2px 8px rgba(0,0,0,0.18)",
          transition: "all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)",
          transform: isOpen ? "scale(0.92) rotate(90deg)" : "scale(1) rotate(0deg)",
        }}
      >
        {isOpen ? (
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round">
            <path d="M18 6L6 18M6 6l12 12" />
          </svg>
        ) : (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
            <circle cx="9" cy="10" r="0.8" fill="white" />
            <circle cx="12" cy="10" r="0.8" fill="white" />
            <circle cx="15" cy="10" r="0.8" fill="white" />
          </svg>
        )}
        {!isOpen && !hasInteracted && (
          <span style={{
            position: "absolute",
            top: "2px",
            right: "2px",
            width: "12px",
            height: "12px",
            background: "#22c55e",
            borderRadius: "50%",
            border: "2px solid white",
            animation: "pulse 2s infinite",
          }} />
        )}
      </button>

      {/* Chat Window */}
      <div
        style={{
          position: "fixed",
          bottom: "104px",
          right: "28px",
          width: "380px",
          maxWidth: "calc(100vw - 32px)",
          height: "560px",
          maxHeight: "calc(100vh - 140px)",
          background: "#0f172a",
          borderRadius: "20px",
          boxShadow: "0 24px 80px rgba(0,0,0,0.5), 0 0 0 1px rgba(255,255,255,0.06)",
          display: "flex",
          flexDirection: "column",
          overflow: "hidden",
          zIndex: 9998,
          opacity: isOpen ? 1 : 0,
          transform: isOpen ? "translateY(0) scale(1)" : "translateY(16px) scale(0.96)",
          pointerEvents: isOpen ? "all" : "none",
          transition: "opacity 0.25s ease, transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1)",
        }}
      >
        {/* Header */}
        <div style={{
          background: "linear-gradient(135deg, #0f172a 0%, #1e293b 100%)",
          padding: "16px 20px",
          borderBottom: "1px solid rgba(255,255,255,0.06)",
          flexShrink: 0,
        }}>
          <div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
            <div style={{
              width: "42px",
              height: "42px",
              borderRadius: "12px",
              background: "linear-gradient(135deg, #16a34a, #22c55e)",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              flexShrink: 0,
              boxShadow: "0 4px 12px rgba(22,163,74,0.4)",
            }}>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M12 2a10 10 0 0 1 10 10c0 5.52-4.48 10-10 10a9.96 9.96 0 0 1-4.96-1.32L2 22l1.32-5.04A9.96 9.96 0 0 1 2 12 10 10 0 0 1 12 2z"/>
                <path d="M8 10h8M8 14h5" />
              </svg>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                color: "white",
                fontWeight: 700,
                fontSize: "15px",
                letterSpacing: "-0.01em",
              }}>
                Aasi — AI Assistant
              </div>
              <div style={{
                color: "#94a3b8",
                fontSize: "12px",
                marginTop: "1px",
                display: "flex",
                alignItems: "center",
                gap: "5px",
              }}>
                <span style={{
                  width: "6px",
                  height: "6px",
                  borderRadius: "50%",
                  background: "#22c55e",
                  display: "inline-block",
                  animation: "pulse 2s infinite",
                }} />
                Online · Aasi Technologies
              </div>
            </div>
            <div style={{
              background: "rgba(22,163,74,0.1)",
              border: "1px solid rgba(22,163,74,0.2)",
              borderRadius: "8px",
              padding: "4px 10px",
              fontSize: "11px",
              color: "#4ade80",
              fontWeight: 600,
              letterSpacing: "0.04em",
            }}>
              AI
            </div>
          </div>
        </div>

        {/* Messages Area */}
        <div style={{
          flex: 1,
          overflowY: "auto",
          padding: "20px 16px",
          display: "flex",
          flexDirection: "column",
          gap: "12px",
          scrollbarWidth: "thin",
          scrollbarColor: "rgba(255,255,255,0.1) transparent",
        }}>
          {/* Welcome State */}
          {messages.length === 0 && (
            <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
              {/* Bot welcome message */}
              <div style={{ display: "flex", gap: "10px", alignItems: "flex-start" }}>
                <div style={{
                  width: "30px",
                  height: "30px",
                  borderRadius: "8px",
                  background: "linear-gradient(135deg, #16a34a, #22c55e)",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  flexShrink: 0,
                  marginTop: "2px",
                }}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round">
                    <circle cx="12" cy="8" r="4" />
                    <path d="M6 20v-2a6 6 0 0 1 12 0v2" />
                  </svg>
                </div>
                <div style={{
                  background: "rgba(255,255,255,0.05)",
                  border: "1px solid rgba(255,255,255,0.08)",
                  borderRadius: "4px 16px 16px 16px",
                  padding: "12px 14px",
                  maxWidth: "calc(100% - 48px)",
                }}>
                  <p style={{ color: "#e2e8f0", fontSize: "14px", lineHeight: "1.6", margin: 0 }}>
                    Hey there! 👋 I'm Aasi, your guide to everything Aasi Technologies offers.
                  </p>
                  <p style={{ color: "#94a3b8", fontSize: "13px", lineHeight: "1.6", margin: "8px 0 0" }}>
                    Whether you're looking to build a web app, launch a mobile product, or explore AI solutions — I'm here to help you find the right fit.
                  </p>
                </div>
              </div>

              {/* Suggested questions */}
              <div style={{ paddingLeft: "40px" }}>
                <p style={{ color: "#64748b", fontSize: "11px", marginBottom: "8px", letterSpacing: "0.06em", fontWeight: 600 }}>
                  QUICK QUESTIONS
                </p>
                <div style={{ display: "flex", flexDirection: "column", gap: "6px" }}>
                  {SUGGESTED_QUESTIONS.map((q) => (
                    <button
                      key={q}
                      onClick={() => handleSuggestion(q)}
                      style={{
                        background: "rgba(22,163,74,0.07)",
                        border: "1px solid rgba(22,163,74,0.15)",
                        borderRadius: "10px",
                        padding: "9px 14px",
                        color: "#86efac",
                        fontSize: "13px",
                        cursor: "pointer",
                        textAlign: "left",
                        transition: "all 0.15s ease",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "space-between",
                        gap: "8px",
                      }}
                      onMouseEnter={(e) => {
                        e.currentTarget.style.background = "rgba(22,163,74,0.14)";
                        e.currentTarget.style.borderColor = "rgba(22,163,74,0.3)";
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.background = "rgba(22,163,74,0.07)";
                        e.currentTarget.style.borderColor = "rgba(22,163,74,0.15)";
                      }}
                    >
                      {q}
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" style={{ flexShrink: 0, opacity: 0.7 }}>
                        <path d="M5 12h14M12 5l7 7-7 7" />
                      </svg>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* Chat Messages */}
          {messages.map((message) => {
            const messageText = message.parts
              ?.map((part) => (part.type === "text" ? part.text : ""))
              .join("")
              .trim();

            const isUser = message.role === "user";

            return (
              <div
                key={message.id}
                style={{
                  display: "flex",
                  flexDirection: isUser ? "row-reverse" : "row",
                  gap: "10px",
                  alignItems: "flex-start",
                }}
              >
                {!isUser && (
                  <div style={{
                    width: "30px",
                    height: "30px",
                    borderRadius: "8px",
                    background: "linear-gradient(135deg, #16a34a, #22c55e)",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    flexShrink: 0,
                    marginTop: "2px",
                  }}>
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round">
                      <circle cx="12" cy="8" r="4" />
                      <path d="M6 20v-2a6 6 0 0 1 12 0v2" />
                    </svg>
                  </div>
                )}

                <div style={{
                  background: isUser
                    ? "linear-gradient(135deg, #16a34a, #15803d)"
                    : "rgba(255,255,255,0.05)",
                  border: isUser ? "none" : "1px solid rgba(255,255,255,0.08)",
                  borderRadius: isUser ? "16px 4px 16px 16px" : "4px 16px 16px 16px",
                  padding: "11px 14px",
                  maxWidth: "calc(100% - 48px)",
                  color: isUser ? "white" : "#e2e8f0",
                  fontSize: "14px",
                  lineHeight: "1.6",
                  boxShadow: isUser ? "0 4px 12px rgba(22,163,74,0.25)" : "none",
                }}>
                  {messageText || "..."}
                </div>
              </div>
            );
          })}

          {/* Typing indicator */}
          {isLoading && (
            <div style={{ display: "flex", gap: "10px", alignItems: "flex-start" }}>
              <div style={{
                width: "30px",
                height: "30px",
                borderRadius: "8px",
                background: "linear-gradient(135deg, #16a34a, #22c55e)",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                flexShrink: 0,
              }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round">
                  <circle cx="12" cy="8" r="4" />
                  <path d="M6 20v-2a6 6 0 0 1 12 0v2" />
                </svg>
              </div>
              <div style={{
                background: "rgba(255,255,255,0.05)",
                border: "1px solid rgba(255,255,255,0.08)",
                borderRadius: "4px 16px 16px 16px",
                padding: "14px 18px",
                display: "flex",
                alignItems: "center",
                gap: "5px",
              }}>
                {[0, 1, 2].map((i) => (
                  <span
                    key={i}
                    style={{
                      width: "7px",
                      height: "7px",
                      borderRadius: "50%",
                      background: "#22c55e",
                      display: "inline-block",
                      animation: `typingBounce 1.2s ease-in-out ${i * 0.2}s infinite`,
                      opacity: 0.7,
                    }}
                  />
                ))}
              </div>
            </div>
          )}

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

        {/* Input Area */}
        <div style={{
          padding: "12px 14px 16px",
          borderTop: "1px solid rgba(255,255,255,0.06)",
          background: "rgba(15,23,42,0.95)",
          flexShrink: 0,
        }}>
          <form onSubmit={handleFormSubmit} style={{ position: "relative" }}>
            <input
              ref={inputRef}
              type="text"
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              placeholder="Ask me anything..."
              disabled={isLoading}
              style={{
                width: "100%",
                background: "rgba(255,255,255,0.06)",
                border: "1px solid rgba(255,255,255,0.1)",
                borderRadius: "12px",
                padding: "12px 52px 12px 16px",
                color: "white",
                fontSize: "14px",
                outline: "none",
                boxSizing: "border-box",
                transition: "border-color 0.15s ease",
                fontFamily: "inherit",
              }}
              onFocus={(e) => {
                e.target.style.borderColor = "rgba(22,163,74,0.5)";
                e.target.style.boxShadow = "0 0 0 3px rgba(22,163,74,0.1)";
              }}
              onBlur={(e) => {
                e.target.style.borderColor = "rgba(255,255,255,0.1)";
                e.target.style.boxShadow = "none";
              }}
            />
            <button
              type="submit"
              disabled={isLoading || !inputValue.trim()}
              style={{
                position: "absolute",
                right: "8px",
                top: "50%",
                transform: "translateY(-50%)",
                width: "36px",
                height: "36px",
                borderRadius: "9px",
                background: inputValue.trim()
                  ? "linear-gradient(135deg, #16a34a, #22c55e)"
                  : "rgba(255,255,255,0.06)",
                border: "none",
                cursor: inputValue.trim() ? "pointer" : "not-allowed",
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                transition: "all 0.2s ease",
                opacity: isLoading ? 0.5 : 1,
              }}
            >
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z" />
              </svg>
            </button>
          </form>
          <div style={{
            marginTop: "8px",
            textAlign: "center",
            color: "#475569",
            fontSize: "11px",
            letterSpacing: "0.02em",
          }}>
            Powered by Aasi Technologies AI
          </div>
        </div>
      </div>

      <style>{`
        @keyframes pulse {
          0%, 100% { opacity: 1; transform: scale(1); }
          50% { opacity: 0.6; transform: scale(0.85); }
        }
        @keyframes typingBounce {
          0%, 60%, 100% { transform: translateY(0); opacity: 0.5; }
          30% { transform: translateY(-6px); opacity: 1; }
        }
        *::-webkit-scrollbar { width: 4px; }
        *::-webkit-scrollbar-track { background: transparent; }
        *::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 4px; }
      `}</style>
    </>
  );
}