"use client";

import * as React from "react";

export interface Message {
  id: string;
  content: string;
  sender: "user" | "ai";
  timestamp: Date;
  type?: "text" | "error" | "system";
  isStreaming?: boolean;
}

interface ChatDockProps {
  isOpen: boolean;
  onClose: () => void;
  onMinimize?: () => void;
  onSendMessage: (message: string) => void;
  messages: Message[];
  isTyping?: boolean;
  title?: string;
  placeholder?: string;
  className?: string;
  maxHeight?: string;
  position?: "bottom-right" | "bottom-left" | "center";
  showHeader?: boolean;
  allowMinimize?: boolean;
  disabled?: boolean;
}

export function ChatDock({
  isOpen,
  onClose,
  onMinimize,
  onSendMessage,
  messages,
  isTyping = false,
  title = "Chat",
  placeholder = "Type your message...",
  className = "",
  maxHeight = "600px",
  position = "bottom-right",
  showHeader = true,
  allowMinimize = true,
  disabled = false,
}: ChatDockProps) {
  const [inputValue, setInputValue] = React.useState("");
  const [isMinimized, setIsMinimized] = React.useState(false);
  const messagesEndRef = React.useRef<HTMLDivElement>(null);
  const inputRef = React.useRef<HTMLInputElement>(null);

  // Auto-scroll to bottom when new messages arrive
  React.useEffect(() => {
    if (messagesEndRef.current && !isMinimized) {
      messagesEndRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [messages, isMinimized]);

  // Focus input when dock opens
  React.useEffect(() => {
    if (isOpen && !isMinimized && inputRef.current) {
      const timer = setTimeout(() => {
        inputRef.current?.focus();
      }, 100);
      return () => clearTimeout(timer);
    }
  }, [isOpen, isMinimized]);

  const handleSendMessage = React.useCallback(() => {
    const trimmedValue = inputValue.trim();
    if (trimmedValue && !disabled) {
      onSendMessage(trimmedValue);
      setInputValue("");
    }
  }, [inputValue, onSendMessage, disabled]);

  const handleKeyPress = React.useCallback(
    (event: React.KeyboardEvent) => {
      if (event.key === "Enter" && !event.shiftKey) {
        event.preventDefault();
        handleSendMessage();
      }
    },
    [handleSendMessage]
  );

  const handleMinimize = React.useCallback(() => {
    setIsMinimized(!isMinimized);
    if (onMinimize) {
      onMinimize();
    }
  }, [isMinimized, onMinimize]);

  const getPositionClasses = () => {
    switch (position) {
      case "bottom-left":
        return "bottom-24 left-6";
      case "center":
        return "top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2";
      default:
        return "bottom-24 right-6";
    }
  };

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

  if (!isOpen) return null;

  return (
    <div
      className={`
        fixed z-40 
        ${getPositionClasses()}
        w-96 max-w-[calc(100vw-2rem)]
        bg-white 
        rounded-2xl 
        shadow-2xl 
        border 
        border-gray-200
        transition-all 
        duration-300 
        ease-in-out
        ${isMinimized ? "h-16" : ""}
        ${className}
        md:w-96 w-[calc(100vw-2rem)]
      `}
      style={{ maxHeight: isMinimized ? "64px" : maxHeight }}
      role="dialog"
      aria-label={title}
    >
      {/* Header */}
      {showHeader && (
        <div className="flex items-center justify-between p-4 border-b border-gray-200 bg-gray-50 rounded-t-2xl">
          <h3 className="font-semibold text-gray-800 text-lg">{title}</h3>
          <div className="flex items-center space-x-2">
            {allowMinimize && (
              <button
                onClick={handleMinimize}
                className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-200 rounded-full transition-colors"
                aria-label="Minimize chat"
              >
                <svg
                  className="w-4 h-4"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M20 12H4"
                  />
                </svg>
              </button>
            )}
            <button
              onClick={onClose}
              className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-200 rounded-full transition-colors"
              aria-label="Close chat"
            >
              <svg
                className="w-4 h-4"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M6 18L18 6M6 6l12 12"
                />
              </svg>
            </button>
          </div>
        </div>
      )}

      {/* Messages Container */}
      {!isMinimized && (
        <>
          <div
            className="flex-1 overflow-y-auto p-4 space-y-4"
            style={{ maxHeight: "400px" }}
          >
            {messages.map((message) => {
              const isUser = message.sender === "user";
              const isError = message.type === "error";
              const isSystem = message.type === "system";

              return (
                <div
                  key={message.id}
                  className={`flex ${
                    isUser ? "justify-end" : "justify-start"
                  } mb-4`}
                >
                  <div
                    className={`
                      max-w-[85%] px-4 py-3 rounded-2xl shadow-sm
                      ${
                        isUser
                          ? "bg-blue-600 text-white rounded-br-md"
                          : isError
                          ? "bg-red-50 text-red-800 border border-red-200 rounded-bl-md"
                          : isSystem
                          ? "bg-gray-50 text-gray-600 border border-gray-200 rounded-bl-md"
                          : "bg-gray-100 text-gray-800 rounded-bl-md"
                      }
                      ${message.isStreaming ? "animate-pulse" : ""}
                    `}
                  >
                    <div className="text-sm leading-relaxed whitespace-pre-wrap break-words">
                      {message.content}
                    </div>
                    <div
                      className={`text-xs mt-1 opacity-70 ${
                        isUser ? "text-blue-100" : "text-gray-500"
                      }`}
                    >
                      {formatTimestamp(message.timestamp)}
                    </div>
                  </div>
                </div>
              );
            })}

            {/* Typing Indicator */}
            {isTyping && (
              <div className="flex items-center space-x-2 px-4 py-3">
                <div className="flex space-x-1">
                  <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce [animation-delay:-0.3s]"></div>
                  <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce [animation-delay:-0.15s]"></div>
                  <div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
                </div>
                <span className="text-sm text-gray-500">Typing...</span>
              </div>
            )}

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

          {/* Input Area */}
          <div className="p-4 border-t border-gray-200 bg-gray-50 rounded-b-2xl">
            <div className="flex space-x-3">
              <input
                ref={inputRef}
                type="text"
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                onKeyPress={handleKeyPress}
                placeholder={placeholder}
                disabled={disabled}
                className="flex-1 px-4 py-2 border border-gray-300 rounded-full focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed"
                maxLength={1000}
              />
              <button
                onClick={handleSendMessage}
                disabled={!inputValue.trim() || disabled}
                className="px-6 py-2 bg-blue-600 text-white rounded-full hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                aria-label="Send message"
              >
                <svg
                  className="w-4 h-4"
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"
                  />
                </svg>
              </button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

export default ChatDock;
