"use client";

import React, { useState, useRef, useEffect, useCallback } from "react";
import { ArrowLeft, Send, Menu, X } from "lucide-react";
import { Button } from "../../ui/Button";
import SuggestedQuestions from "./suggested-questions";
import { useI18n, RTLText } from "./i18n-context";

interface MobileFullscreenChatProps {
  onSendMessage: (message: string) => void;
  onBackPress?: () => void;
  messages?: Array<{
    id: string;
    text: string;
    isUser: boolean;
    timestamp: Date;
  }>;
  isTyping?: boolean;
  title?: string;
  placeholder?: string;
  className?: string;
  disabled?: boolean;
  showSuggestedQuestions?: boolean;
  suggestedQuestionsContext?: string;
  /** Custom header content */
  headerContent?: React.ReactNode;
  /** Whether to show keyboard adjustment */
  keyboardAdjustment?: boolean;
  /** Custom mobile breakpoint */
  mobileBreakpoint?: number;
  /** Whether to enable pull-to-refresh */
  pullToRefresh?: boolean;
}

interface ViewportState {
  height: number;
  width: number;
  keyboardVisible: boolean;
  keyboardHeight: number;
}

// Hook for detecting viewport changes and keyboard
function useViewport(): ViewportState {
  const [viewport, setViewport] = useState<ViewportState>({
    height: typeof window !== "undefined" ? window.innerHeight : 0,
    width: typeof window !== "undefined" ? window.innerWidth : 0,
    keyboardVisible: false,
    keyboardHeight: 0,
  });

  useEffect(() => {
    if (typeof window === "undefined") return;

    const updateViewport = () => {
      const newHeight = window.innerHeight;
      const newWidth = window.innerWidth;

      // Estimate keyboard visibility based on height change
      const heightDiff = viewport.height - newHeight;
      const keyboardVisible = heightDiff > 150; // Threshold for keyboard detection

      setViewport({
        height: newHeight,
        width: newWidth,
        keyboardVisible,
        keyboardHeight: keyboardVisible ? heightDiff : 0,
      });
    };

    const handleResize = () => {
      updateViewport();
    };

    const handleVisualViewportChange = () => {
      if ("visualViewport" in window && window.visualViewport) {
        const vvHeight = window.visualViewport.height;
        const windowHeight = window.innerHeight;
        const keyboardHeight = windowHeight - vvHeight;
        const keyboardVisible = keyboardHeight > 150;

        setViewport((prev) => ({
          ...prev,
          height: vvHeight,
          keyboardVisible,
          keyboardHeight,
        }));
      }
    };

    window.addEventListener("resize", handleResize);

    // Use Visual Viewport API if available (better for keyboard detection)
    if ("visualViewport" in window && window.visualViewport) {
      window.visualViewport.addEventListener(
        "resize",
        handleVisualViewportChange
      );
    }

    // Initial update
    updateViewport();

    return () => {
      window.removeEventListener("resize", handleResize);
      if ("visualViewport" in window && window.visualViewport) {
        window.visualViewport.removeEventListener(
          "resize",
          handleVisualViewportChange
        );
      }
    };
  }, [viewport.height]);

  return viewport;
}

export function MobileFullscreenChat({
  onSendMessage,
  onBackPress,
  messages = [],
  isTyping = false,
  title,
  placeholder,
  className = "",
  disabled = false,
  showSuggestedQuestions = true,
  suggestedQuestionsContext,
  headerContent,
  keyboardAdjustment = true,
  mobileBreakpoint = 768,
  pullToRefresh = false,
}: MobileFullscreenChatProps) {
  const [inputMessage, setInputMessage] = useState("");
  const [isMenuOpen, setIsMenuOpen] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const {
    height: viewportHeight,
    keyboardVisible,
    keyboardHeight,
  } = useViewport();

  const inputRef = useRef<HTMLInputElement>(null);
  const messagesContainerRef = useRef<HTMLDivElement>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // Add missing dir variable
  const dir = "ltr"; // Default direction, can be made configurable

  // Add translation function (simplified)
  const t = (key: string, fallback: string) => fallback;

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

  // Handle keyboard appearance adjustments
  useEffect(() => {
    if (!keyboardAdjustment) return;

    const chatContainer = messagesContainerRef.current;
    if (chatContainer && keyboardVisible) {
      // Scroll to show latest messages when keyboard appears
      setTimeout(() => {
        messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
      }, 100);
    }
  }, [keyboardVisible, keyboardAdjustment]);

  const handleSendMessage = useCallback(() => {
    if (inputMessage.trim() && !disabled) {
      onSendMessage(inputMessage.trim());
      setInputMessage("");
      inputRef.current?.focus();
    }
  }, [inputMessage, disabled, onSendMessage]);

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

  const handleSuggestedQuestionClick = useCallback((question: string) => {
    setInputMessage(question);
    inputRef.current?.focus();
  }, []);

  const handleBackPress = useCallback(() => {
    if (onBackPress) {
      onBackPress();
    } else if (typeof window !== "undefined" && window.history.length > 1) {
      window.history.back();
    }
  }, [onBackPress]);

  // Pull-to-refresh handler
  const handlePullToRefresh = useCallback(async () => {
    if (!pullToRefresh) return;

    setRefreshing(true);
    // Simulate refresh action
    await new Promise((resolve) => setTimeout(resolve, 1000));
    setRefreshing(false);
  }, [pullToRefresh]);

  // Calculate dynamic styles for keyboard adjustment
  const containerStyle: React.CSSProperties = {
    height: keyboardAdjustment ? `${viewportHeight}px` : "100vh",
    width: "100vw",
    maxHeight: keyboardAdjustment ? `${viewportHeight}px` : "100vh",
    overflow: "hidden",
  };

  const messagesAreaHeight =
    keyboardAdjustment && keyboardVisible
      ? viewportHeight - 64 - 80 // Header height - Input area height
      : viewportHeight - 64 - 80;

  return (
    <div
      className={`mobile-fullscreen-chat ${className}`}
      style={containerStyle}
      dir={dir}
    >
      {/* Header */}
      <header className="mobile-chat-header">
        <div className="header-content">
          <Button
            variant="ghost"
            size="sm"
            onClick={handleBackPress}
            className="back-button"
            aria-label={t("chat.back", "Back")}
          >
            <ArrowLeft size={24} />
          </Button>

          <div className="header-title">
            <h1>{title || t("chat.title", "Chat")}</h1>
          </div>

          {headerContent || (
            <Button
              variant="ghost"
              size="sm"
              onClick={() => setIsMenuOpen(!isMenuOpen)}
              className="menu-button"
              aria-label={t("chat.menu", "Menu")}
            >
              {isMenuOpen ? <X size={24} /> : <Menu size={24} />}
            </Button>
          )}
        </div>

        {/* Menu dropdown */}
        {isMenuOpen && (
          <div className="mobile-menu">
            <div className="menu-item">
              <button onClick={() => setIsMenuOpen(false)}>
                {t("chat.clearHistory", "Clear History")}
              </button>
            </div>
            <div className="menu-item">
              <button onClick={() => setIsMenuOpen(false)}>
                {t("chat.settings", "Settings")}
              </button>
            </div>
          </div>
        )}
      </header>

      {/* Messages Area */}
      <div
        className="messages-area"
        style={{ height: `${messagesAreaHeight}px` }}
        ref={messagesContainerRef}
      >
        {refreshing && (
          <div className="refresh-indicator">
            <div className="refresh-spinner" />
            <span>{t("chat.refreshing", "Refreshing...")}</span>
          </div>
        )}

        <div className="messages-container">
          {messages.length === 0 && !isTyping ? (
            <div className="empty-state">
              <div className="empty-icon">💬</div>
              <h2>{t("chat.welcome", "Welcome to Chat")}</h2>
              <p>
                {t(
                  "chat.welcomeMessage",
                  "Start a conversation by typing a message below."
                )}
              </p>

              {showSuggestedQuestions && (
                <div className="suggested-questions-mobile">
                  <SuggestedQuestions
                    context={suggestedQuestionsContext}
                    onQuestionClick={handleSuggestedQuestionClick}
                    className="mobile-suggestions"
                  />
                </div>
              )}
            </div>
          ) : (
            <>
              {messages.map((message) => (
                <div
                  key={message.id}
                  className={`message ${
                    message.isUser ? "user-message" : "ai-message"
                  }`}
                >
                  <div className="message-content">
                    <RTLText text={message.text} />
                  </div>
                  <div className="message-time">
                    {message.timestamp.toLocaleTimeString([], {
                      hour: "2-digit",
                      minute: "2-digit",
                    })}
                  </div>
                </div>
              ))}

              {isTyping && (
                <div className="message ai-message typing">
                  <div className="message-content">
                    <div className="typing-indicator">
                      <span></span>
                      <span></span>
                      <span></span>
                    </div>
                  </div>
                </div>
              )}
            </>
          )}
          <div ref={messagesEndRef} />
        </div>
      </div>

      {/* Input Area */}
      <div className="input-area">
        <div className="input-container">
          <input
            ref={inputRef}
            type="text"
            value={inputMessage}
            onChange={(e) => setInputMessage(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder={
              placeholder || t("chat.placeholder", "Type your message...")
            }
            disabled={disabled}
            className="message-input"
            aria-label={t("chat.inputLabel", "Message input")}
          />
          <Button
            onClick={handleSendMessage}
            disabled={!inputMessage.trim() || disabled}
            className="send-button"
            aria-label={t("chat.send", "Send message")}
          >
            <Send size={20} />
          </Button>
        </div>
      </div>

      <style jsx>{`
        .mobile-fullscreen-chat {
          position: fixed;
          top: 0;
          left: 0;
          background: white;
          display: flex;
          flex-direction: column;
          z-index: 9999;
        }

        .mobile-chat-header {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
          padding: 0;
          box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
          position: relative;
          min-height: 64px;
        }

        .header-content {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 12px 16px;
          height: 64px;
          box-sizing: border-box;
        }

        .back-button,
        .menu-button {
          color: white;
          min-width: 48px;
          min-height: 48px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .back-button:hover,
        .menu-button:hover {
          background: rgba(255, 255, 255, 0.1);
        }

        .header-title {
          flex: 1;
          text-align: center;
          margin: 0 16px;
        }

        .header-title h1 {
          margin: 0;
          font-size: 18px;
          font-weight: 600;
        }

        .mobile-menu {
          position: absolute;
          top: 100%;
          right: 0;
          background: white;
          border-radius: 8px;
          box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
          margin: 8px;
          min-width: 200px;
          z-index: 1000;
        }

        .menu-item {
          border-bottom: 1px solid #f0f0f0;
        }

        .menu-item:last-child {
          border-bottom: none;
        }

        .menu-item button {
          width: 100%;
          padding: 16px;
          text-align: left;
          background: none;
          border: none;
          font-size: 16px;
          color: #333;
          cursor: pointer;
        }

        .menu-item button:hover {
          background: #f5f5f5;
        }

        .messages-area {
          flex: 1;
          overflow: hidden;
          background: #f8f9fa;
          position: relative;
        }

        .refresh-indicator {
          position: absolute;
          top: 16px;
          left: 50%;
          transform: translateX(-50%);
          display: flex;
          align-items: center;
          gap: 8px;
          background: white;
          padding: 8px 16px;
          border-radius: 20px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          z-index: 10;
        }

        .refresh-spinner {
          width: 16px;
          height: 16px;
          border: 2px solid #f3f3f3;
          border-top: 2px solid #667eea;
          border-radius: 50%;
          animation: spin 1s linear infinite;
        }

        @keyframes spin {
          0% {
            transform: rotate(0deg);
          }
          100% {
            transform: rotate(360deg);
          }
        }

        .messages-container {
          height: 100%;
          overflow-y: auto;
          padding: 16px;
          display: flex;
          flex-direction: column;
          gap: 12px;
          -webkit-overflow-scrolling: touch;
        }

        .empty-state {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100%;
          text-align: center;
          padding: 20px;
        }

        .empty-icon {
          font-size: 48px;
          margin-bottom: 16px;
        }

        .empty-state h2 {
          font-size: 24px;
          margin: 0 0 8px 0;
          color: #333;
        }

        .empty-state p {
          font-size: 16px;
          color: #666;
          margin: 0 0 24px 0;
          line-height: 1.5;
        }

        .suggested-questions-mobile {
          width: 100%;
          max-width: 400px;
        }

        .message {
          display: flex;
          flex-direction: column;
          max-width: 85%;
          word-wrap: break-word;
          margin-bottom: 4px;
        }

        .user-message {
          align-self: flex-end;
          align-items: flex-end;
        }

        .ai-message {
          align-self: flex-start;
          align-items: flex-start;
        }

        .message-content {
          padding: 16px 20px;
          border-radius: 20px;
          font-size: 16px;
          line-height: 1.4;
          min-height: 20px;
          word-break: break-word;
        }

        .user-message .message-content {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
          border-bottom-right-radius: 8px;
        }

        .ai-message .message-content {
          background: white;
          color: #333;
          border: 1px solid #e1e5e9;
          border-bottom-left-radius: 8px;
        }

        .message-time {
          font-size: 12px;
          color: #888;
          margin: 4px 8px 0;
        }

        .typing-indicator {
          display: flex;
          gap: 4px;
          align-items: center;
        }

        .typing-indicator span {
          height: 8px;
          width: 8px;
          background: #999;
          border-radius: 50%;
          animation: typing 1.4s infinite ease-in-out;
        }

        .typing-indicator span:nth-child(1) {
          animation-delay: -0.32s;
        }

        .typing-indicator span:nth-child(2) {
          animation-delay: -0.16s;
        }

        @keyframes typing {
          0%,
          80%,
          100% {
            transform: scale(0.8);
            opacity: 0.5;
          }
          40% {
            transform: scale(1);
            opacity: 1;
          }
        }

        .input-area {
          background: white;
          border-top: 1px solid #e1e5e9;
          padding: 16px;
          min-height: 80px;
          display: flex;
          align-items: center;
        }

        .input-container {
          display: flex;
          gap: 12px;
          width: 100%;
          align-items: flex-end;
        }

        .message-input {
          flex: 1;
          min-height: 48px;
          padding: 12px 16px;
          border: 2px solid #e1e5e9;
          border-radius: 24px;
          font-size: 16px;
          outline: none;
          background: #f8f9fa;
          resize: none;
          box-sizing: border-box;
        }

        .message-input:focus {
          border-color: #667eea;
          background: white;
        }

        .send-button {
          min-width: 48px;
          min-height: 48px;
          border-radius: 50%;
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
          border: none;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          transition: all 0.2s ease;
        }

        .send-button:enabled:hover {
          transform: scale(1.05);
          box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
        }

        .send-button:disabled {
          background: #ccc;
          cursor: not-allowed;
          transform: none;
          box-shadow: none;
        }

        /* Dark mode support */
        @media (prefers-color-scheme: dark) {
          .mobile-fullscreen-chat {
            background: #1a1a1a;
            color: white;
          }

          .messages-area {
            background: #2d2d2d;
          }

          .ai-message .message-content {
            background: #3a3a3a;
            color: white;
            border-color: #555;
          }

          .empty-state h2 {
            color: white;
          }

          .empty-state p {
            color: #ccc;
          }

          .message-input {
            background: #3a3a3a;
            color: white;
            border-color: #555;
          }

          .message-input:focus {
            background: #4a4a4a;
          }

          .input-area {
            background: #2d2d2d;
            border-color: #555;
          }

          .mobile-menu {
            background: #3a3a3a;
            color: white;
          }

          .menu-item button {
            color: white;
          }

          .menu-item button:hover {
            background: #4a4a4a;
          }
        }

        /* High contrast mode */
        @media (prefers-contrast: high) {
          .message-content {
            border-width: 2px;
          }

          .send-button:focus {
            outline: 3px solid #fff;
            outline-offset: 2px;
          }

          .back-button:focus,
          .menu-button:focus {
            outline: 2px solid #fff;
            outline-offset: 2px;
          }
        }

        /* Reduced motion */
        @media (prefers-reduced-motion: reduce) {
          .typing-indicator span {
            animation: none;
          }

          .refresh-spinner {
            animation: none;
          }

          .send-button:enabled:hover {
            transform: none;
          }
        }
      `}</style>
    </div>
  );
}
