import { useState, useEffect, useRef } from 'react';

interface Message {
  role: 'user' | 'assistant';
  content: string;
}

interface ChatSession {
  id: string;
  messages: Message[];
  collected_data: Record<string, string>;
  missing_fields: string[];
  status: string;
}

// Pencil Design Colors
const colors = {
  primary: '#213A7E',
  primaryDark: '#152850',
  primaryLight: '#4A6BA8',
  primaryShadow: '#213A7E40',
  textDark: '#1A1A1A',
  textGray: '#666666',
  textLight: '#888888',
  bgLight: '#FAFAFA',
  border: '#E5E5E5',
  white: '#FFFFFF',
  placeholder: '#999999',
  badge: '#EF4444',
  success: '#22C55E',
};

// Generate a unique visitor ID
const getVisitorId = (): string => {
  const key = 'sharetone_visitor_id';
  let id = localStorage.getItem(key);
  if (!id) {
    id = 'v_' + Math.random().toString(36).substring(2) + Date.now().toString(36);
    localStorage.setItem(key, id);
  }
  return id;
};

export default function ChatWidget() {
  const [isOpen, setIsOpen] = useState(false);
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [sessionId, setSessionId] = useState<string | null>(null);
  const [isComplete, setIsComplete] = useState(false);
  const [ipCountry, setIpCountry] = useState<string | null>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // Initial greeting
  const greetingMessage: Message = {
    role: 'assistant',
    content: 'Hola, ¿estás buscando maletas o algún otro producto? Estoy aquí para ayudarte.',
  };

  // Scroll to bottom when messages change
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  // Load existing session and detect IP location on mount
  useEffect(() => {
    const loadSession = async () => {
      try {
        const visitorId = getVisitorId();
        const response = await fetch(`/api/chatbot?visitor_id=${visitorId}`);
        const data = await response.json();

        if (data.session && data.session.status === 'active') {
          setSessionId(data.session.id);
          setMessages(data.session.messages || []);
          if (data.session.messages?.length === 0) {
            setMessages([greetingMessage]);
          }
        }
      } catch (error) {
        console.error('Error loading session:', error);
      }
    };

    // Detect visitor location via IP (informational only, not used as lead's country)
    const detectLocation = async () => {
      try {
        const res = await fetch('https://ipapi.co/json/');
        const data = await res.json();
        if (data.country_name) {
          setIpCountry(data.country_name);
        }
      } catch {
        // Silent fail - location detection is optional
      }
    };

    loadSession();
    detectLocation();
  }, []);

  // Initialize with greeting when opened for first time
  useEffect(() => {
    if (isOpen && messages.length === 0) {
      setMessages([greetingMessage]);
    }
  }, [isOpen]);

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

    const userMessage = input.trim();
    setInput('');
    setMessages((prev) => [...prev, { role: 'user', content: userMessage }]);
    setIsLoading(true);

    try {
      const response = await fetch('/api/chatbot', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          message: userMessage,
          session_id: sessionId,
          visitor_id: getVisitorId(),
          source_page: window.location.pathname,
          ip_location: ipCountry,
        }),
      });

      const data = await response.json();

      if (data.error) {
        throw new Error(data.error);
      }

      setSessionId(data.session_id);
      setMessages((prev) => [...prev, { role: 'assistant', content: data.response }]);

      if (data.is_complete) {
        setIsComplete(true);
      }
    } catch (error) {
      console.error('Error sending message:', error);
      setMessages((prev) => [
        ...prev,
        { role: 'assistant', content: 'Lo siento, hubo un error. ¿Podrías intentar de nuevo?' },
      ]);
    } finally {
      setIsLoading(false);
    }
  };

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

  const resetChat = () => {
    localStorage.removeItem('sharetone_visitor_id');
    setSessionId(null);
    setMessages([greetingMessage]);
    setIsComplete(false);
  };

  // Bot Avatar Component
  const BotAvatar = ({ size = 28 }: { size?: number }) => (
    <div
      style={{
        width: size,
        height: size,
        borderRadius: size / 2,
        backgroundColor: colors.primary,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        flexShrink: 0,
      }}
    >
      <svg
        width={size * 0.57}
        height={size * 0.57}
        viewBox="0 0 24 24"
        fill="none"
        stroke={colors.white}
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      >
        <path d="M12 8V4H8" />
        <rect width="16" height="12" x="4" y="8" rx="2" />
        <path d="M2 14h2" />
        <path d="M20 14h2" />
        <path d="M15 13v2" />
        <path d="M9 13v2" />
      </svg>
    </div>
  );

  return (
    <>
      {/* Floating Chat Button - Pencil Design */}
      {!isOpen && (
        <button
          onClick={() => setIsOpen(true)}
          style={{
            position: 'fixed',
            bottom: 24,
            right: 24,
            zIndex: 50,
            width: 64,
            height: 64,
            borderRadius: 32,
            backgroundColor: colors.primaryDark,
            border: 'none',
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            boxShadow: `0 4px 16px ${colors.primaryShadow}`,
            transition: 'transform 0.2s ease',
          }}
          onMouseEnter={(e) => (e.currentTarget.style.transform = 'scale(1.05)')}
          onMouseLeave={(e) => (e.currentTarget.style.transform = 'scale(1)')}
          aria-label="Abrir chat"
        >
          {/* Message Circle Icon */}
          <svg
            width="28"
            height="28"
            viewBox="0 0 24 24"
            fill="none"
            stroke={colors.white}
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z" />
          </svg>
        </button>
      )}

      {/* Chat Window - Pencil Design */}
      {isOpen && (
        <div
          style={{
            position: 'fixed',
            bottom: 24,
            right: 24,
            zIndex: 50,
            width: 380,
            height: 625,
            maxHeight: 'calc(100vh - 48px)',
            borderRadius: 16,
            backgroundColor: colors.white,
            boxShadow: '0 8px 32px rgba(0, 0, 0, 0.12)',
            display: 'flex',
            flexDirection: 'column',
            overflow: 'hidden',
            fontFamily: "'Inter', sans-serif",
          }}
        >
          {/* Header - Pencil Design */}
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'space-between',
              backgroundColor: colors.primaryDark,
              padding: '16px 20px',
              borderRadius: '16px 16px 0 0',
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              {/* Avatar */}
              <div
                style={{
                  width: 40,
                  height: 40,
                  borderRadius: 20,
                  backgroundColor: colors.white,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
              >
                <svg
                  width="22"
                  height="22"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke={colors.primary}
                  strokeWidth="2"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                >
                  <rect x="3" y="11" width="18" height="10" rx="2" />
                  <path d="M12 11V7" />
                  <circle cx="12" cy="5" r="2" />
                  <path d="M8 15h.01M16 15h.01" />
                  <path d="M1 14h2M21 14h2" />
                </svg>
              </div>
              {/* Info */}
              <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', gap: 2 }}>
                <span
                  style={{
                    fontSize: 15,
                    fontWeight: 600,
                    color: colors.white,
                  }}
                >
                  Asistente Virtual
                </span>
                <span
                  style={{
                    fontSize: 11,
                    color: colors.white,
                    opacity: 0.85,
                    lineHeight: 1.3,
                    maxWidth: 220,
                  }}
                >
                  Estoy aquí para ayudarte a encontrar lo que necesitas.
                </span>
              </div>
            </div>
            {/* Close Button */}
            <button
              onClick={() => setIsOpen(false)}
              style={{
                width: 32,
                height: 32,
                borderRadius: 16,
                backgroundColor: 'transparent',
                border: 'none',
                cursor: 'pointer',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                transition: 'background-color 0.2s',
              }}
              onMouseEnter={(e) => (e.currentTarget.style.backgroundColor = 'rgba(255,255,255,0.1)')}
              onMouseLeave={(e) => (e.currentTarget.style.backgroundColor = 'transparent')}
              aria-label="Cerrar chat"
            >
              <svg
                width="18"
                height="18"
                viewBox="0 0 24 24"
                fill="none"
                stroke={colors.white}
                strokeWidth="2"
                strokeLinecap="round"
                strokeLinejoin="round"
              >
                <path d="M18 6 6 18" />
                <path d="m6 6 12 12" />
              </svg>
            </button>
          </div>

          {/* Messages Body - Pencil Design */}
          <div
            style={{
              flex: 1,
              minHeight: 0,
              backgroundColor: colors.bgLight,
              padding: 16,
              overflowY: 'auto',
              overscrollBehavior: 'contain',
              display: 'flex',
              flexDirection: 'column',
              gap: 16,
            }}
          >
            {messages.map((msg, index) => (
              <div
                key={index}
                style={{
                  display: 'flex',
                  alignItems: 'flex-end',
                  gap: 8,
                  justifyContent: msg.role === 'user' ? 'flex-end' : 'flex-start',
                  width: '100%',
                }}
              >
                {/* Bot Avatar */}
                {msg.role === 'assistant' && <BotAvatar />}

                {/* Message Bubble */}
                <div
                  style={{
                    maxWidth: 220,
                    padding: '12px 16px',
                    borderRadius:
                      msg.role === 'user'
                        ? '16px 16px 4px 16px'
                        : '16px 16px 16px 4px',
                    backgroundColor: msg.role === 'user' ? colors.primary : colors.white,
                    color: msg.role === 'user' ? colors.white : colors.textDark,
                  }}
                >
                  <p
                    style={{
                      fontSize: 14,
                      lineHeight: 1.5,
                      margin: 0,
                      whiteSpace: 'pre-wrap',
                      fontFamily: "'Inter', sans-serif",
                    }}
                  >
                    {msg.content.trim()}
                  </p>
                </div>
              </div>
            ))}

            {/* Loading Indicator */}
            {isLoading && (
              <div
                style={{
                  display: 'flex',
                  alignItems: 'flex-end',
                  gap: 8,
                }}
              >
                <BotAvatar />
                <div
                  style={{
                    padding: '12px 16px',
                    borderRadius: '16px 16px 16px 4px',
                    backgroundColor: colors.white,
                  }}
                >
                  <div style={{ display: 'flex', gap: 4 }}>
                    {[0, 1, 2].map((i) => (
                      <span
                        key={i}
                        style={{
                          width: 8,
                          height: 8,
                          borderRadius: 4,
                          backgroundColor: colors.textLight,
                          animation: 'bounce 1s infinite',
                          animationDelay: `${i * 150}ms`,
                        }}
                      />
                    ))}
                  </div>
                </div>
              </div>
            )}

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

          {/* Input Area - Pencil Design */}
          <div
            style={{
              backgroundColor: colors.white,
              padding: 16,
              borderTop: `1px solid ${colors.border}`,
              borderRadius: '0 0 16px 16px',
            }}
          >
            {isComplete ? (
              <div style={{ textAlign: 'center' }}>
                <p
                  style={{
                    fontSize: 14,
                    color: colors.textGray,
                    marginBottom: 12,
                  }}
                >
                  Conversación completada
                </p>
                <button
                  onClick={resetChat}
                  style={{
                    padding: '12px 24px',
                    backgroundColor: colors.primary,
                    color: colors.white,
                    border: 'none',
                    borderRadius: 8,
                    fontSize: 14,
                    fontWeight: 600,
                    cursor: 'pointer',
                    fontFamily: "'Inter', sans-serif",
                  }}
                >
                  Nueva conversación
                </button>
              </div>
            ) : (
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                {/* Input Field */}
                <div
                  style={{
                    flex: 1,
                    backgroundColor: colors.bgLight,
                    borderRadius: 24,
                    padding: '12px 16px',
                  }}
                >
                  <input
                    type="text"
                    value={input}
                    onChange={(e) => setInput(e.target.value)}
                    onKeyDown={handleKeyDown}
                    placeholder="Escribe un mensaje..."
                    disabled={isLoading}
                    style={{
                      width: '100%',
                      border: 'none',
                      backgroundColor: 'transparent',
                      fontSize: 14,
                      color: colors.textDark,
                      outline: 'none',
                      boxShadow: 'none',
                      WebkitAppearance: 'none',
                      fontFamily: "'Inter', sans-serif",
                    }}
                  />
                </div>
                {/* Send Button */}
                <button
                  onClick={sendMessage}
                  disabled={isLoading || !input.trim()}
                  style={{
                    width: 44,
                    height: 44,
                    borderRadius: 22,
                    backgroundColor: isLoading || !input.trim() ? colors.border : colors.primary,
                    border: 'none',
                    cursor: isLoading || !input.trim() ? 'not-allowed' : 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    flexShrink: 0,
                    transition: 'background-color 0.2s',
                  }}
                  aria-label="Enviar mensaje"
                >
                  <svg
                    width="20"
                    height="20"
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke={colors.white}
                    strokeWidth="2"
                    strokeLinecap="round"
                    strokeLinejoin="round"
                  >
                    <path d="m22 2-7 20-4-9-9-4Z" />
                    <path d="M22 2 11 13" />
                  </svg>
                </button>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Animation Styles */}
      <style>{`
        @keyframes bounce {
          0%, 60%, 100% {
            transform: translateY(0);
          }
          30% {
            transform: translateY(-4px);
          }
        }
      `}</style>
    </>
  );
}
