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

// ─── Types ────────────────────────────────────────────────────────────────────
interface ChatMessage {
  role: 'user' | 'assistant';
  content: string;
  ts: number;
}

export type UbaidiContext = 'platform' | 'shop' | 'admin' | 'landing';

interface UbaidiChatProps {
  context: UbaidiContext;
  /** Optional: tenant token for shop/admin/landing contexts */
  tenantToken?: string;
  /** Optional extra info for landing page or admin dashboard */
  extra?: { 
    productId?: string; 
    productName?: string;
    todaySales?: number;
    todayOrdersCount?: number;
    totalSales?: number;
    totalOrdersCount?: number;
    [key: string]: any;
  };
  /** Optional: custom API base (defaults to /php-api) */
  apiBase?: string;
}

// ─── Context labels ───────────────────────────────────────────────────────────
const CONTEXT_LABELS: Record<UbaidiContext, string> = {
  platform: 'ShophyFast সম্পর্কে যেকোনো প্রশ্ন করুন...',
  shop:     'পণ্য, দাম, ডেলিভারি সম্পর্কে জিজ্ঞেস করুন...',
  admin:    'Shop analytics, business tips জিজ্ঞেস করুন...',
  landing:  'এই পণ্য সম্পর্কে যেকোনো প্রশ্ন করুন...',
};

// ─── Ubaidi Chat Widget ───────────────────────────────────────────────────────
export default function UbaidiChat({ context, tenantToken, extra, apiBase = '/php-api' }: UbaidiChatProps) {
  const [open, setOpen] = useState(false);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [pulse, setPulse] = useState(true);
  const bottomRef = useRef<HTMLDivElement>(null);
  const inputRef  = useRef<HTMLInputElement>(null);

  // Stop pulsing after user opens chat
  useEffect(() => {
    if (open) { setPulse(false); inputRef.current?.focus(); }
  }, [open]);

  // Scroll to bottom on new message
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages, loading]);

  // Send message
  const send = async () => {
    const text = input.trim();
    if (!text || loading) return;

    const userMsg: ChatMessage = { role: 'user', content: text, ts: Date.now() };
    setMessages(prev => [...prev, userMsg]);
    setInput('');
    setLoading(true);

    try {
      const history = messages.slice(-8).map(m => ({ role: m.role, content: m.content }));
      const res = await fetch(`/api/openrouter/chat`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(tenantToken ? { 'X-Tenant-Token': tenantToken } : {}),
        },
        body: JSON.stringify({ message: text, context, history, extra }),
      });
      const data = await res.json();
      setMessages(prev => [...prev, { role: 'assistant', content: data.reply || 'দুঃখিত, উত্তর দিতে পারিনি।', ts: Date.now() }]);
    } catch {
      setMessages(prev => [...prev, { role: 'assistant', content: '❌ সংযোগ সমস্যা। একটু পরে চেষ্টা করুন।', ts: Date.now() }]);
    } finally {
      setLoading(false);
    }
  };

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

  return (
    <>
      {/* ── Chat Panel ────────────────────────────────────────────────────── */}
      {open && (
        <div
          className="fixed z-[9998] right-4 bottom-[calc(5rem+env(safe-area-inset-bottom,0px))] md:right-5 md:bottom-24 w-[360px] max-w-[calc(100vw-32px)]"
          style={{
            background: 'linear-gradient(160deg,#0d0b1e 0%,#111827 100%)',
            border: '1px solid rgba(139,92,246,0.25)',
            borderRadius: '24px',
            boxShadow: '0 32px 80px rgba(0,0,0,0.7), 0 0 0 1px rgba(139,92,246,0.1)',
            backdropFilter: 'blur(20px)',
            display: 'flex',
            flexDirection: 'column',
            overflow: 'hidden',
            animation: 'ubaidiSlideUp 0.3s cubic-bezier(0.34,1.56,0.64,1)',
          }}
        >
          {/* Header */}
          <div style={{
            background: 'linear-gradient(135deg,rgba(124,58,237,0.3),rgba(79,70,229,0.2))',
            borderBottom: '1px solid rgba(139,92,246,0.15)',
            padding: '14px 16px',
            display: 'flex',
            alignItems: 'center',
            gap: '10px',
          }}>
            {/* Avatar */}
            <div style={{
              width: '38px', height: '38px', borderRadius: '50%', flexShrink: 0,
              background: 'linear-gradient(135deg,#7c3aed,#4f46e5)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '0 0 16px rgba(124,58,237,0.5)',
            }}>
              <svg width="20" height="20" 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" fill="rgba(255,255,255,0.15)" />
              </svg>
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <p style={{ margin: 0, fontWeight: 900, fontSize: '14px', color: '#fff', letterSpacing: '-0.3px' }}>Ubaidi AI</p>
              <p style={{ margin: 0, fontSize: '11px', color: '#a78bfa', fontWeight: 600 }}>
                {context === 'admin' ? 'Shop Assistant' : context === 'platform' ? 'ShophyFast Guide' : 'এখনই সাহায্য করতে প্রস্তুত ✨'}
              </p>
            </div>
            <button
              onClick={() => setOpen(false)}
              style={{
                background: 'rgba(255,255,255,0.08)', border: 'none', cursor: 'pointer',
                width: '28px', height: '28px', borderRadius: '50%', color: '#94a3b8',
                fontSize: '14px', display: 'flex', alignItems: 'center', justifyContent: 'center',
                transition: 'all 0.2s',
              }}
              onMouseEnter={e => (e.currentTarget.style.background = 'rgba(255,255,255,0.15)')}
              onMouseLeave={e => (e.currentTarget.style.background = 'rgba(255,255,255,0.08)')}
            >✕</button>
          </div>

          {/* Messages */}
          <div style={{
            flex: 1, overflowY: 'auto', padding: '14px 14px 8px',
            minHeight: '280px', maxHeight: '380px',
            scrollbarWidth: 'thin', scrollbarColor: 'rgba(124,58,237,0.3) transparent',
          }}>
            {messages.length === 0 && (
              <div style={{ textAlign: 'center', padding: '24px 8px' }}>
                <div style={{ width: '52px', height: '52px', borderRadius: '50%', background: 'linear-gradient(135deg,rgba(124,58,237,0.2),rgba(79,70,229,0.15))', border: '1px solid rgba(124,58,237,0.3)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 12px' }}>
                  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#a78bfa" 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" fill="rgba(167,139,250,0.1)" />
                  </svg>
                </div>
                <p style={{ color: '#a78bfa', fontWeight: 700, fontSize: '14px', margin: '0 0 6px' }}>আমি Ubaidi!</p>
                <p style={{ color: '#64748b', fontSize: '12px', margin: 0, lineHeight: 1.6 }}>
                  {CONTEXT_LABELS[context]}
                </p>
              </div>
            )}

            {messages.map((m, i) => (
              <div key={i} style={{
                display: 'flex',
                justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start',
                marginBottom: '10px',
              }}>
                {m.role === 'assistant' && (
                  <div style={{
                    width: '26px', height: '26px', borderRadius: '50%', flexShrink: 0,
                    background: 'linear-gradient(135deg,#7c3aed,#4f46e5)',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    marginRight: '7px', marginTop: '2px',
                  }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" 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" />
                    </svg>
                  </div>
                )}
                <div style={{
                  maxWidth: '80%',
                  padding: '9px 13px',
                  borderRadius: m.role === 'user' ? '16px 16px 4px 16px' : '16px 16px 16px 4px',
                  background: m.role === 'user'
                    ? 'linear-gradient(135deg,#7c3aed,#4f46e5)'
                    : 'rgba(255,255,255,0.06)',
                  border: m.role === 'assistant' ? '1px solid rgba(139,92,246,0.15)' : 'none',
                  color: '#f1f5f9',
                  fontSize: '13px',
                  lineHeight: 1.6,
                  fontWeight: 500,
                  whiteSpace: 'pre-wrap',
                  wordBreak: 'break-word',
                }}>{m.content}</div>
              </div>
            ))}

            {loading && (
              <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '10px' }}>
                <div style={{
                  width: '26px', height: '26px', borderRadius: '50%', flexShrink: 0,
                  background: 'linear-gradient(135deg,#7c3aed,#4f46e5)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" 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" />
                  </svg>
                </div>
                <div style={{
                  padding: '10px 14px',
                  background: 'rgba(255,255,255,0.06)',
                  border: '1px solid rgba(139,92,246,0.15)',
                  borderRadius: '16px 16px 16px 4px',
                  display: 'flex', gap: '4px', alignItems: 'center',
                }}>
                  {[0, 1, 2].map(i => (
                    <div key={i} style={{
                      width: '6px', height: '6px', borderRadius: '50%',
                      background: '#7c3aed',
                      animation: `ubaidiDot 1.2s ease-in-out ${i * 0.2}s infinite`,
                    }} />
                  ))}
                </div>
              </div>
            )}
            <div ref={bottomRef} />
          </div>

          {/* Input */}
          <div style={{
            display: 'flex', gap: '8px', padding: '12px 14px',
            borderTop: '1px solid rgba(139,92,246,0.12)',
            background: 'rgba(0,0,0,0.2)',
          }}>
            <input
              ref={inputRef}
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={handleKey}
              placeholder={CONTEXT_LABELS[context].split('...')[0] + '...'}
              disabled={loading}
              style={{
                flex: 1,
                background: 'rgba(255,255,255,0.06)',
                border: '1px solid rgba(139,92,246,0.2)',
                borderRadius: '12px',
                padding: '9px 13px',
                color: '#f1f5f9',
                fontSize: '13px',
                outline: 'none',
                transition: 'border-color 0.2s',
              }}
              onFocus={e => (e.target.style.borderColor = 'rgba(139,92,246,0.6)')}
              onBlur={e => (e.target.style.borderColor = 'rgba(139,92,246,0.2)')}
            />
            <button
              onClick={send}
              disabled={!input.trim() || loading}
              style={{
                width: '38px', height: '38px', borderRadius: '12px',
                background: input.trim() && !loading
                  ? 'linear-gradient(135deg,#7c3aed,#4f46e5)'
                  : 'rgba(124,58,237,0.2)',
                border: 'none', cursor: input.trim() && !loading ? 'pointer' : 'not-allowed',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                transition: 'all 0.2s', flexShrink: 0,
                boxShadow: input.trim() && !loading ? '0 4px 12px rgba(124,58,237,0.4)' : 'none',
              }}
            >
              <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <line x1="22" y1="2" x2="11" y2="13" /><polygon points="22 2 15 22 11 13 2 9 22 2" />
              </svg>
            </button>
          </div>
        </div>
      )}

      {/* ── Floating Trigger Button ───────────────────────────────────────── */}
      <button
        id="ubaidi-chat-trigger"
        onClick={() => setOpen(o => !o)}
        title="Ubaidi AI দিয়ে সাহায্য নিন"
        className="fixed z-[9999] right-4 bottom-[calc(5rem+env(safe-area-inset-bottom,0px))] md:right-5 md:bottom-5 flex items-center justify-center w-12 h-12 md:w-14 md:h-14 rounded-full"
        style={{
          background: open
            ? 'linear-gradient(135deg,#4f46e5,#7c3aed)'
            : 'linear-gradient(135deg,#7c3aed,#4f46e5)',
          border: 'none',
          cursor: 'pointer',
          boxShadow: '0 8px 32px rgba(124,58,237,0.5), 0 0 0 0 rgba(124,58,237,0.4)',
          animation: pulse ? 'ubaidiPulse 2s ease-in-out infinite' : 'none',
          transition: 'transform 0.2s, box-shadow 0.2s',
        }}
        onMouseEnter={e => {
          e.currentTarget.style.transform = 'scale(1.1)';
          e.currentTarget.style.boxShadow = '0 12px 40px rgba(124,58,237,0.6)';
        }}
        onMouseLeave={e => {
          e.currentTarget.style.transform = 'scale(1)';
          e.currentTarget.style.boxShadow = '0 8px 32px rgba(124,58,237,0.5)';
        }}
      >
        {open ? (
          <svg className="w-4 h-4 md:w-5 md:h-5" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
          </svg>
        ) : (
          <svg className="w-5 h-5 md:w-6 md:h-6" 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" fill="rgba(255,255,255,0.15)" />
        </svg>
        )}
        {/* Notification dot */}
        {!open && messages.length === 0 && (
          <span style={{
            position: 'absolute', top: '2px', right: '2px',
            width: '12px', height: '12px', borderRadius: '50%',
            background: '#22c55e',
            border: '2px solid #0d0b1e',
            animation: 'ubaidiDotBlink 1.5s ease-in-out infinite',
          }} />
        )}
      </button>

      {/* ── CSS Animations ───────────────────────────────────────────────── */}
      <style>{`
        @keyframes ubaidiPulse {
          0%, 100% { box-shadow: 0 8px 32px rgba(124,58,237,0.5), 0 0 0 0 rgba(124,58,237,0.35); }
          50%       { box-shadow: 0 8px 32px rgba(124,58,237,0.5), 0 0 0 12px rgba(124,58,237,0); }
        }
        @keyframes ubaidiDot {
          0%, 80%, 100% { transform: scale(0.6); opacity: 0.4; }
          40%           { transform: scale(1); opacity: 1; }
        }
        @keyframes ubaidiSlideUp {
          from { opacity: 0; transform: translateY(20px) scale(0.96); }
          to   { opacity: 1; transform: translateY(0) scale(1); }
        }
        @keyframes ubaidiDotBlink {
          0%, 100% { opacity: 1; }
          50%      { opacity: 0.3; }
        }
        #ubaidi-chat-trigger:active { transform: scale(0.94) !important; }
      `}</style>
    </>
  );
}
