const { useState, useRef, useEffect, useCallback } = React;

// ─── Stepper steps ──────────────────────────────────────────
const CHAT_STEPS = [
  { id: 'qualification', label: 'Qualification' },
  { id: 'documents',     label: 'Documents' },
  { id: 'paiement',     label: 'Paiement' },
  { id: 'analyse',      label: 'Analyse' },
  { id: 'rapport',      label: 'Rapport' }
];

function Chat({ dossierId, onPaymentComplete }) {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [checkoutUrl, setCheckoutUrl] = useState(null);
  const [currentStep, setCurrentStep] = useState(0);
  const messagesEndRef = useRef(null);
  const textareaRef = useRef(null);

  // Auto-scroll
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  // Premier message automatique
  useEffect(() => {
    if (dossierId && messages.length === 0) {
      sendMessage("Bonjour");
    }
  }, [dossierId]);

  // Auto-resize textarea
  useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
      textareaRef.current.style.height = Math.min(textareaRef.current.scrollHeight, 120) + 'px';
    }
  }, [input]);

  // Advance stepper based on conversation state
  useEffect(() => {
    if (checkoutUrl) setCurrentStep(2);
    else if (messages.length > 4) setCurrentStep(1);
  }, [messages.length, checkoutUrl]);

  const PAID_STATUTS = ['paid', 'analysing', 'building_expert', 'costing', 'reviewing', 'challenging', 'drafting', 'delivered', 'error'];

  const pollForPayment = useCallback((id) => {
    const pollInterval = setInterval(async () => {
      try {
        const res = await fetch(`/api/session/${id}`);
        if (!res.ok) return;
        const data = await res.json();
        if (data.statut && PAID_STATUTS.includes(data.statut)) {
          clearInterval(pollInterval);
          if (onPaymentComplete) onPaymentComplete();
        }
      } catch (e) { /* silence */ }
    }, 5000);

    // Cleanup after 30 min max
    setTimeout(() => clearInterval(pollInterval), 30 * 60 * 1000);
  }, [onPaymentComplete]);

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

    // Sanitize input client-side
    const sanitized = userText
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .slice(0, 5000);

    if (text !== "Bonjour") {
      setMessages(prev => [...prev, { role: 'user', content: sanitized }]);
    }
    setInput('');
    setIsLoading(true);

    try {
      const response = await fetch(`/api/session/${dossierId}/chat`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ message: sanitized })
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      let assistantText = '';
      let quickActions = [];

      setMessages(prev => [...prev, { role: 'assistant', content: '', quickActions: [] }]);

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);
        const lines = chunk.split('\n');

        for (const line of lines) {
          if (!line.startsWith('data: ')) continue;

          try {
            const data = JSON.parse(line.slice(6));

            if (data.type === 'text') {
              assistantText += data.content;
              setMessages(prev => {
                const updated = [...prev];
                updated[updated.length - 1] = { role: 'assistant', content: assistantText, quickActions };
                return updated;
              });
            }

            if (data.type === 'quick_actions' && Array.isArray(data.actions)) {
              quickActions = data.actions;
              setMessages(prev => {
                const updated = [...prev];
                updated[updated.length - 1] = { ...updated[updated.length - 1], quickActions };
                return updated;
              });
            }

            if (data.type === 'tool' && data.name === 'create_checkout' && data.result?.checkoutUrl) {
              setCheckoutUrl(data.result.checkoutUrl);
              pollForPayment(dossierId);
            }

            if (data.type === 'error') {
              assistantText += '\n\n⚠ Erreur technique, veuillez reessayer.';
              setMessages(prev => {
                const updated = [...prev];
                updated[updated.length - 1] = { role: 'assistant', content: assistantText, quickActions: [] };
                return updated;
              });
            }
          } catch (e) { /* ignore non-JSON */ }
        }
      }
    } catch (err) {
      setMessages(prev => [...prev, {
        role: 'assistant',
        content: 'Erreur de connexion. Veuillez rafraichir la page et reessayer.',
        quickActions: []
      }]);
    } finally {
      setIsLoading(false);
    }
  }, [dossierId, input, isLoading]);

  const handleKeyDown = useCallback((e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  }, [sendMessage]);

  function formatText(text) {
    if (!text) return '';
    return text
      .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      .replace(/\n/g, '<br/>');
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', flex: 1, overflow: 'hidden' }}>

      {/* ── Stepper ─────────────────────────────────────── */}
      <div style={{
        background: '#fff', borderBottom: '1px solid #e7e5e4',
        padding: '.75rem 1.5rem', display: 'flex', alignItems: 'center', gap: 0,
        overflowX: 'auto', scrollbarWidth: 'none'
      }}>
        {CHAT_STEPS.map((step, i) => (
          <React.Fragment key={step.id}>
            {i > 0 && (
              <div style={{
                width: 20, height: 1, margin: '0 4px', flexShrink: 0,
                background: i <= currentStep ? '#10b981' : '#e7e5e4'
              }}></div>
            )}
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap' }}>
              <div className={i === currentStep ? 'anim-pulse' : ''} style={{
                width: 24, height: 24, borderRadius: '50%',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: '.65rem', fontWeight: 700, flexShrink: 0, transition: 'all .3s',
                ...(i < currentStep
                  ? { background: '#10b981', color: '#fff' }
                  : i === currentStep
                    ? { background: '#f59e0b', color: '#fff', boxShadow: '0 0 0 4px rgba(245,158,11,.2)' }
                    : { background: '#fafaf9', color: '#a8a29e', border: '1px solid #e7e5e4' })
              }}>
                {i < currentStep ? '✓' : i + 1}
              </div>
              <span style={{
                fontSize: '.65rem',
                color: i === currentStep ? '#f59e0b' : '#a8a29e',
                fontWeight: i === currentStep ? 600 : 400,
                maxWidth: 60, overflow: 'hidden', textOverflow: 'ellipsis'
              }}>
                {step.label}
              </span>
            </div>
          </React.Fragment>
        ))}
      </div>

      {/* ── Messages ────────────────────────────────────── */}
      <div className="chat-scroll" style={{ flex: 1, overflowY: 'auto', padding: '1.5rem', display: 'flex', flexDirection: 'column', gap: '1rem' }}>

        {messages.map((msg, i) => (
          <div key={i} className="anim-fade-in" style={{
            display: 'flex', gap: '.75rem', maxWidth: '85%',
            alignSelf: msg.role === 'user' ? 'flex-end' : 'flex-start',
            flexDirection: msg.role === 'user' ? 'row-reverse' : 'row'
          }}>
            {/* Avatar */}
            <div style={{
              width: 32, height: 32, borderRadius: 10,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: '.7rem', fontWeight: 700, flexShrink: 0,
              ...(msg.role === 'assistant'
                ? { background: 'linear-gradient(135deg, #f59e0b, #f97316)', color: '#fff' }
                : { background: '#18181b', color: '#fff' })
            }}>
              {msg.role === 'assistant' ? 'AI' : (
                <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>
                </svg>
              )}
            </div>

            <div>
              {/* Bubble */}
              <div style={{
                padding: '.875rem 1.125rem', borderRadius: 16, fontSize: '.875rem', lineHeight: 1.6,
                ...(msg.role === 'user'
                  ? { background: '#18181b', color: '#fff', borderBottomRightRadius: 4 }
                  : { background: '#fff', border: '1px solid #e7e5e4', color: '#1c1917', borderBottomLeftRadius: 4 })
              }}>
                <span dangerouslySetInnerHTML={{ __html: formatText(msg.content) }} />
              </div>

              {/* Quick actions */}
              {msg.role === 'assistant' && msg.quickActions?.length > 0 && (
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 6 }} className="anim-fade-in">
                  {msg.quickActions.map((action, j) => (
                    <button
                      key={j}
                      onClick={() => sendMessage(action)}
                      style={{
                        background: 'rgba(245,158,11,.08)', border: '1px solid rgba(245,158,11,.2)',
                        color: '#f59e0b', padding: '6px 14px', borderRadius: 20,
                        fontSize: '.75rem', fontWeight: 500, cursor: 'pointer', transition: 'all .2s'
                      }}
                      onMouseOver={e => { e.target.style.background = 'rgba(245,158,11,.15)'; e.target.style.transform = 'translateY(-1px)' }}
                      onMouseOut={e => { e.target.style.background = 'rgba(245,158,11,.08)'; e.target.style.transform = 'translateY(0)' }}
                    >
                      {action}
                    </button>
                  ))}
                </div>
              )}
            </div>
          </div>
        ))}

        {/* Typing indicator */}
        {isLoading && messages[messages.length - 1]?.role !== 'assistant' && (
          <div className="anim-fade-in" style={{ display: 'flex', gap: '.75rem', alignSelf: 'flex-start' }}>
            <div style={{
              width: 32, height: 32, borderRadius: 10,
              background: 'linear-gradient(135deg, #f59e0b, #f97316)', color: '#fff',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: '.7rem', fontWeight: 700
            }}>AI</div>
            <div style={{
              display: 'flex', gap: 4, padding: '1rem 1.125rem',
              background: '#fff', border: '1px solid #e7e5e4',
              borderRadius: 16, borderBottomLeftRadius: 4, width: 'fit-content'
            }}>
              <span className="typing-dot" style={{ width: 6, height: 6, borderRadius: '50%', background: '#a8a29e' }}></span>
              <span className="typing-dot" style={{ width: 6, height: 6, borderRadius: '50%', background: '#a8a29e' }}></span>
              <span className="typing-dot" style={{ width: 6, height: 6, borderRadius: '50%', background: '#a8a29e' }}></span>
            </div>
          </div>
        )}

        {/* Bouton paiement */}
        {checkoutUrl && (
          <div className="anim-fade-up" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '1rem', padding: '1.5rem 0' }}>
            <div style={{
              width: '100%', maxWidth: 380, padding: '2rem', borderRadius: 20,
              border: '2px solid #f59e0b', textAlign: 'center',
              background: 'rgba(245,158,11,.03)', boxShadow: '0 8px 30px rgba(245,158,11,.1)'
            }}>
              <div className="anim-pulse-glow" style={{
                width: 56, height: 56, borderRadius: 16, margin: '0 auto 1rem',
                background: 'linear-gradient(135deg, #f59e0b, #d97706)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                boxShadow: '0 4px 16px rgba(245,158,11,.3)'
              }}>
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="2">
                  <rect width="20" height="14" x="2" y="5" rx="2"/><line x1="2" x2="22" y1="10" y2="10"/>
                </svg>
              </div>
              <p style={{ fontWeight: 700, fontSize: '1.1rem', color: '#1c1917', marginBottom: '.25rem' }}>
                Votre dossier est pret
              </p>
              <p style={{ fontSize: '.85rem', color: '#78716c', marginBottom: '1.5rem' }}>
                Lancez l'analyse pour recevoir votre rapport par email
              </p>
              <a
                href={checkoutUrl}
                target="_blank"
                rel="noopener noreferrer"
                style={{
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                  width: '100%', padding: 14, borderRadius: 12,
                  background: 'linear-gradient(135deg, #059669, #047857)',
                  color: '#fff', fontSize: '.95rem', fontWeight: 600,
                  textDecoration: 'none', transition: 'all .2s'
                }}
              >
                <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10"/>
                </svg>
                Payer et lancer l'analyse
              </a>
              <p style={{ fontSize: '.7rem', color: '#a8a29e', marginTop: '.75rem' }}>
                Paiement securise via Stripe — Droit de retractation L221-28
              </p>
            </div>
          </div>
        )}

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

      {/* ── Input bar ───────────────────────────────────── */}
      <div style={{
        background: '#fff', borderTop: '1px solid #e7e5e4', padding: '1rem 1.5rem'
      }}>
        <div style={{ display: 'flex', gap: '.75rem', alignItems: 'flex-end' }}>
          <textarea
            ref={textareaRef}
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={handleKeyDown}
            placeholder="Decrivez votre situation..."
            rows={1}
            maxLength={5000}
            disabled={isLoading}
            style={{
              flex: 1, padding: '.75rem 1rem', borderRadius: 12,
              border: '1px solid #e7e5e4', background: '#fafaf9',
              fontSize: '.875rem', fontFamily: 'inherit', resize: 'none',
              outline: 'none', minHeight: 42, maxHeight: 120,
              transition: 'border .2s', color: '#1c1917',
              opacity: isLoading ? 0.5 : 1
            }}
            onFocus={e => e.target.style.borderColor = '#f59e0b'}
            onBlur={e => e.target.style.borderColor = '#e7e5e4'}
          />
          <button
            onClick={() => sendMessage()}
            disabled={isLoading || !input.trim()}
            style={{
              width: 42, height: 42, borderRadius: 12, border: 'none',
              cursor: input.trim() && !isLoading ? 'pointer' : 'not-allowed',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              transition: 'all .2s', color: '#fff', flexShrink: 0,
              background: input.trim() && !isLoading ? '#f59e0b' : '#d6d3d1',
              opacity: isLoading || !input.trim() ? 0.5 : 1
            }}
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
              <path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/>
            </svg>
          </button>
        </div>
        <p style={{ textAlign: 'center', fontSize: '.65rem', color: '#a8a29e', marginTop: 6 }}>
          Vos donnees sont chiffrees et supprimees sous 90 jours (RGPD)
        </p>
      </div>
    </div>
  );
}
