﻿'use client';
import { useEffect, useState, useRef, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Navbar from '@/components/Navbar';
import api from '@/lib/api';
import { getUser, isLoggedIn } from '@/lib/auth';

const AVATAR_COLORS = ['#1B3A8C', '#E85C1A', '#7c3aed', '#0891b2', '#16a34a', '#dc2626'];

function avatarColor(str) {
  if (!str) return AVATAR_COLORS[0];
  let h = 0;
  for (let i = 0; i < str.length; i++) h = str.charCodeAt(i) + ((h << 5) - h);
  return AVATAR_COLORS[Math.abs(h) % AVATAR_COLORS.length];
}

const apiBase = process.env.NEXT_PUBLIC_API_URL?.replace(/\/api$/, '');

function threadAvatar(pic, name, size = 38) {
  if (pic) {
    const src = pic.startsWith('http') ? pic : `${apiBase}${pic}`;
    return <img src={src} alt="" style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover', flexShrink: 0 }} />;
  }
  const initials = name?.split(' ').map(n => n[0]).join('').slice(0, 2).toUpperCase() || '?';
  return (
    <div style={{ width: size, height: size, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: size > 38 ? '.82rem' : '.78rem', fontWeight: 900, color: '#fff', background: avatarColor(name), flexShrink: 0 }}>
      {initials}
    </div>
  );
}

function MensajesContent() {
  const router       = useRouter();
  const searchParams = useSearchParams();
  const [threads, setThreads] = useState([]);
  const [active, setActive]   = useState(null);
  const [msgs, setMsgs]       = useState([]);
  const [text, setText]       = useState('');
  const [loading, setLoading] = useState(true);
  const [sending, setSending] = useState(false);
  const [deal, setDeal]       = useState(null);
  const [review, setReview]   = useState({ rating: 0, comment: '' });
  const [reviewed, setReviewed] = useState(false);
  const bottomRef = useRef(null);
  const me = typeof window !== 'undefined' ? getUser() : null;

  useEffect(() => {
    if (!isLoggedIn()) { router.push('/login'); return; }
    api.get('/messages/threads')
      .then(r => {
        const rows = Array.isArray(r.data.data) ? r.data.data : [];
        setThreads(rows);

        const userId   = searchParams.get('user');
        const userName = searchParams.get('name') || 'Usuario';
        const reqTitle = searchParams.get('req')  || '';
        const reqId    = searchParams.get('req_id') || null;
        if (userId) {
          const existing = rows.find(t =>
            String(t.other_user_id) === String(userId) &&
            (reqId ? String(t.requirement_id) === String(reqId) : true)
          );
          setActive(existing
            ? existing
            : { other_user_id: Number(userId), other_user_name: userName, requirement_title: reqTitle, requirement_id: reqId ? Number(reqId) : null, _new: true }
          );
        }
      })
      .catch(console.error)
      .finally(() => setLoading(false));
  }, []);

  // Load deal context when active conversation changes
  useEffect(() => {
    if (!active?.other_user_id) { setDeal(null); return; }
    api.get('/deals')
      .then(r => {
        const deals = Array.isArray(r.data.data) ? r.data.data : [];
        const related = deals.find(d =>
          (d.buyer_id === me?.id && d.seller_id === active.other_user_id) ||
          (d.seller_id === me?.id && d.buyer_id === active.other_user_id)
        );
        setDeal(related || null);
        if (related) {
          // Check if current user already reviewed this deal (reviews left about the other party)
          api.get(`/reviews/user/${active.other_user_id}`)
            .then(r => {
              const reviews = Array.isArray(r.data.data?.reviews) ? r.data.data.reviews : [];
              setReviewed(reviews.some(rv => rv.deal_id === related.id && rv.reviewer_id === me?.id));
            })
            .catch(() => setReviewed(false));
        } else {
          setReviewed(false);
        }
      })
      .catch(() => setDeal(null));
  }, [active]);

  useEffect(() => {
    if (!active?.other_user_id) return;
    api.get(`/messages/thread/${active.other_user_id}?req_id=${active.requirement_id || ''}`)
      .then(r => setMsgs(Array.isArray(r.data.data) ? r.data.data : []))
      .catch(console.error);
  }, [active?.other_user_id, active?.requirement_id]);

  // Poll active conversation for new messages every 3 s
  useEffect(() => {
    if (!active?.other_user_id || active._new) return;
    const poll = async () => {
      if (document.visibilityState !== 'visible') return;
      try {
        const r = await api.get(`/messages/thread/${active.other_user_id}?req_id=${active.requirement_id || ''}`);
        const fresh = Array.isArray(r.data.data) ? r.data.data : [];
        setMsgs(prev => fresh.length !== prev.length ? fresh : prev);
      } catch {}
    };
    const timer = setInterval(poll, 3000);
    return () => clearInterval(timer);
  }, [active?.other_user_id, active?.requirement_id]);

  // Poll thread list every 8 s to update last message and unread counts
  useEffect(() => {
    const poll = async () => {
      if (document.visibilityState !== 'visible') return;
      try {
        const r = await api.get('/messages/threads');
        setThreads(Array.isArray(r.data.data) ? r.data.data : []);
      } catch {}
    };
    const timer = setInterval(poll, 8000);
    return () => clearInterval(timer);
  }, []);

  useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: 'smooth' }); }, [msgs]);

  const send = async () => {
    if (!text.trim() || !active) return;
    setSending(true);
    try {
      const { data } = await api.post('/messages', {
        receiver_id: active.other_user_id,
        body: text.trim(),
        requirement_id: active.requirement_id || null,
      });
      // If this was a new (no prior messages) thread, add it to the list
      if (active._new) {
        setThreads(prev => [{ ...active, last_message: text.trim(), last_message_at: new Date().toISOString(), _new: false }, ...prev]);
        setActive(a => ({ ...a, _new: false }));
      }
      setMsgs(m => [...m, {
        id: data.data?.id,
        sender_id: me?.id,
        content: text.trim(),
        body: text.trim(),
        created_at: new Date().toISOString(),
      }]);
      setText('');
    } catch (e) { console.error(e); }
    finally { setSending(false); }
  };

  const autoResize = (el) => {
    el.style.height = 'auto';
    el.style.height = Math.min(el.scrollHeight, 120) + 'px';
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100vh', overflow: 'hidden' }}>
      <Navbar />

      <div style={{ flex: 1, display: 'flex', overflow: 'hidden' }}>

        {/* Thread list */}
        <div className={`thread-list flex-col overflow-hidden ${active ? 'hidden md:flex' : 'flex'}`} style={{
          width: 300, minWidth: 300, background: '#fff',
          borderRight: '1px solid #e4e7ed',
        }}>
          <div style={{ padding: '14px 14px 10px', borderBottom: '1px solid #f1f3f6', flexShrink: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: '#f8f9fb', border: '1.5px solid #e4e7ed', borderRadius: 10, padding: '8px 12px' }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#9ba3b2" strokeWidth="2" strokeLinecap="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
              <input type="text" placeholder="Buscar conversaciones..." style={{ flex: 1, background: 'none', border: 'none', outline: 'none', fontSize: '.82rem', color: '#1a2232', fontFamily: 'inherit' }} />
            </div>
          </div>

          <div style={{ flex: 1, overflowY: 'auto' }}>
            {loading ? (
              <div style={{ padding: 20, textAlign: 'center', color: '#9ba3b2', fontSize: '.84rem' }}>Cargando…</div>
            ) : threads.length === 0 && !active?._new ? (
              <div style={{ padding: '48px 20px', textAlign: 'center' }}>
                <div style={{ width: 72, height: 72, borderRadius: 16, background: 'rgba(27,58,140,.08)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 14px' }}>
                  <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#1B3A8C" strokeWidth="1.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>
                <h3 style={{ fontSize: '1rem', fontWeight: 800, color: '#1a2232', marginBottom: 6 }}>Sin conversaciones</h3>
                <p style={{ fontSize: '.83rem', color: '#9ba3b2', maxWidth: 260, margin: '0 auto' }}>Envía un mensaje desde una propuesta para iniciar una conversación.</p>
              </div>
            ) : threads.map(d => {
              const isActive = active?.other_user_id === d.other_user_id && active?.requirement_id == d.requirement_id;
              return (
                <div key={`${d.other_user_id}-${d.requirement_id}`} onClick={() => setActive(d)} style={{
                  display: 'flex', alignItems: 'flex-start', gap: 10,
                  padding: '12px 14px', borderBottom: '1px solid #f1f3f6',
                  cursor: 'pointer', transition: 'background .15s',
                  background: isActive ? 'rgba(27,58,140,.06)' : '',
                  borderLeft: isActive ? '3px solid #1B3A8C' : '3px solid transparent',
                }}
                  onMouseEnter={e => { if (!isActive) e.currentTarget.style.background = '#f8f9fb'; }}
                  onMouseLeave={e => { if (!isActive) e.currentTarget.style.background = ''; }}>
                  {threadAvatar(d.other_user_pic, d.other_user_name, 38)}
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: '.83rem', fontWeight: 700, color: '#1a2232', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', marginBottom: 2 }}>
                      {d.other_user_name || 'Usuario'}
                    </div>
                    <div style={{ fontSize: '.76rem', fontWeight: 600, color: '#1B3A8C', marginBottom: 3, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {d.requirement_title}
                    </div>
                    <div style={{ fontSize: '.75rem', color: '#9ba3b2', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
                      {d.last_message || 'Sin mensajes aún'}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Chat panel */}
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', background: '#f8f9fb' }}>
          {!active ? (
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 14, textAlign: 'center', padding: 40 }}>
              <div style={{ width: 72, height: 72, borderRadius: 16, background: 'rgba(27,58,140,.08)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="#1B3A8C" strokeWidth="1.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>
              <h3 style={{ fontSize: '1rem', fontWeight: 800, color: '#1a2232' }}>Selecciona una conversación</h3>
              <p style={{ fontSize: '.83rem', color: '#9ba3b2', maxWidth: 260, lineHeight: 1.55 }}>Aquí verás los mensajes de tus proyectos y propuestas enviadas.</p>
            </div>
          ) : (
            <>
              {/* Deal banner */}
              {deal && (
                <div style={{ background: deal.status === 'completed' ? '#f0fdf4' : '#eff6ff', borderBottom: '1px solid #e4e7ed', padding: '10px 20px', display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0, flexWrap: 'wrap' }}>
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={deal.status === 'completed' ? '#16a34a' : '#1B3A8C'} strokeWidth="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
                  <span style={{ fontSize: '.82rem', fontWeight: 700, color: deal.status === 'completed' ? '#16a34a' : '#1B3A8C', flex: 1 }}>
                    Trato: {deal.req_title} — {deal.status === 'completed' ? 'Completado' : deal.status === 'cancelled' ? 'Cancelado' : 'Activo'}
                  </span>
                  {deal.status === 'active' && deal.buyer_id === me?.id && (
                    <button onClick={async () => {
                      if (!confirm('¿Marcar este trato como completado?')) return;
                      try {
                        await api.patch(`/deals/${deal.id}/complete`);
                        setDeal(d => ({ ...d, status: 'completed' }));
                      } catch(e) {
                        alert(e.response?.data?.message || 'Error al completar el trato');
                      }
                    }} style={{ fontSize: '.78rem', fontWeight: 700, padding: '5px 14px', borderRadius: 6, border: 'none', background: '#16a34a', color: '#fff', cursor: 'pointer' }}>
                      ✓ Marcar completado
                    </button>
                  )}
                  {deal.status === 'completed' && !reviewed && (
                    <button onClick={() => setReview(r => ({ ...r, _open: !r._open }))}
                      style={{ fontSize: '.78rem', fontWeight: 700, padding: '5px 14px', borderRadius: 6, border: 'none', background: '#f59e0b', color: '#fff', cursor: 'pointer' }}>
                      ★ Dejar reseña
                    </button>
                  )}
                  {deal.status === 'completed' && reviewed && (
                    <span style={{ fontSize: '.78rem', color: '#16a34a', fontWeight: 700 }}>✓ Reseña enviada</span>
                  )}
                </div>
              )}

              {/* Review form */}
              {deal?.status === 'completed' && review._open && !reviewed && (
                <div style={{ background: '#fffbeb', borderBottom: '1px solid #fde68a', padding: '14px 20px', flexShrink: 0 }}>
                  <p style={{ fontSize: '.82rem', fontWeight: 700, color: '#92400e', marginBottom: 10 }}>Califica tu experiencia con {active.other_user_name}</p>
                  <div style={{ display: 'flex', gap: 6, marginBottom: 10 }}>
                    {[1,2,3,4,5].map(i => (
                      <button key={i} onClick={() => setReview(r => ({ ...r, rating: i }))} type="button"
                        style={{ fontSize: '1.4rem', background: 'none', border: 'none', cursor: 'pointer', color: i <= review.rating ? '#f59e0b' : '#d1d5db', lineHeight: 1 }}>★</button>
                    ))}
                  </div>
                  <textarea value={review.comment} onChange={e => setReview(r => ({ ...r, comment: e.target.value }))}
                    placeholder="Comparte tu experiencia (opcional)…" rows={2}
                    style={{ width: '100%', border: '1.5px solid #fde68a', borderRadius: 7, padding: '8px 12px', fontFamily: 'inherit', fontSize: '.84rem', outline: 'none', resize: 'none', marginBottom: 8 }} />
                  <div style={{ display: 'flex', gap: 8 }}>
                    <button onClick={async () => {
                      if (!review.rating) return alert('Selecciona una calificación');
                      try {
                        const isBuyer = deal.buyer_id === me?.id;
                        await api.post('/reviews', { deal_id: deal.id, rating: review.rating, comment: review.comment, type: isBuyer ? 'buyer_to_seller' : 'seller_to_buyer' });
                        setReviewed(true);
                        setReview(r => ({ ...r, _open: false }));
                      } catch(e) {
                        const msg = e.response?.data?.message || '';
                        if (msg.includes('Ya dejaste')) {
                          setReviewed(true);
                          setReview(r => ({ ...r, _open: false }));
                        } else {
                          alert(msg || 'Error al enviar reseña');
                        }
                      }
                    }} style={{ fontSize: '.82rem', fontWeight: 700, padding: '7px 18px', borderRadius: 7, border: 'none', background: '#f59e0b', color: '#fff', cursor: 'pointer' }}>
                      Enviar reseña
                    </button>
                    <button onClick={() => setReview(r => ({ ...r, _open: false }))}
                      style={{ fontSize: '.82rem', fontWeight: 600, padding: '7px 14px', borderRadius: 7, border: '1.5px solid #e2e8f0', background: '#fff', color: '#64748b', cursor: 'pointer' }}>
                      Cancelar
                    </button>
                  </div>
                </div>
              )}

              {/* Chat header */}
              <div style={{ background: '#fff', borderBottom: '1px solid #e4e7ed', padding: '12px 20px', display: 'flex', alignItems: 'center', gap: 12, flexShrink: 0 }}>
                <button onClick={() => setActive(null)} style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 6, color: '#4b5563', fontSize: '.9rem' }}>
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="15 18 9 12 15 6"/></svg>
                </button>
                {threadAvatar(active.other_user_pic, active.other_user_name, 40)}
                <a href={`/usuario/${active.other_user_id}`} style={{ flex: 1, minWidth: 0, textDecoration: 'none', color: 'inherit' }}>
                  <h3 style={{ fontSize: '.9rem', fontWeight: 800, color: '#1a2232', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{active.other_user_name || 'Usuario'}</h3>
                  <p style={{ fontSize: '.75rem', color: '#9ba3b2', marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{active.requirement_title}</p>
                </a>
                {(active.requirement_id || deal?.requirement_id) && (
                  <a href={`/solicitud/${active.requirement_id || deal.requirement_id}`} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: '.76rem', fontWeight: 700, color: '#1B3A8C', background: 'rgba(27,58,140,.07)', borderRadius: 6, padding: '6px 12px' }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>
                    Ver proyecto
                  </a>
                )}
              </div>

              {/* Messages */}
              <div style={{ flex: 1, overflowY: 'auto', padding: 20, display: 'flex', flexDirection: 'column', gap: 6 }}>
                {msgs.length === 0 ? (
                  <div style={{ textAlign: 'center', color: '#9ba3b2', fontSize: '.84rem', padding: '40px 0' }}>Sé el primero en escribir</div>
                ) : msgs.map((m, i) => {
                  const isMine = m.sender_id === me?.id;
                  return (
                    <div key={m.id || i} style={{ display: 'flex', justifyContent: isMine ? 'flex-end' : 'flex-start', marginBottom: 4 }}>
                      <div style={{
                        maxWidth: '68%', padding: '10px 14px', borderRadius: 14, fontSize: '.84rem', lineHeight: 1.5,
                        ...(isMine
                          ? { background: '#1B3A8C', color: '#fff', borderBottomRightRadius: 4 }
                          : { background: '#fff', color: '#1a2232', border: '1px solid #e4e7ed', borderBottomLeftRadius: 4, boxShadow: '0 1px 3px rgba(0,0,0,.08)' }),
                      }}>
                        <p style={{ margin: 0 }}>{m.body || m.content}</p>
                        <span style={{ fontSize: '.68rem', marginTop: 4, display: 'block', color: isMine ? 'rgba(255,255,255,.6)' : '#9ba3b2', textAlign: isMine ? 'right' : 'left' }}>
                          {new Date(m.created_at).toLocaleTimeString('es-MX', { hour: '2-digit', minute: '2-digit' })}
                        </span>
                      </div>
                    </div>
                  );
                })}
                <div ref={bottomRef} />
              </div>

              {/* Input bar */}
              <div style={{ background: '#fff', borderTop: '1px solid #e4e7ed', padding: '12px 16px', display: 'flex', alignItems: 'flex-end', gap: 10, flexShrink: 0 }}>
                <div style={{ flex: 1, background: '#f8f9fb', border: '1.5px solid #e4e7ed', borderRadius: 16, padding: '10px 14px', transition: 'border-color .2s' }}
                  onFocus={e => e.currentTarget.style.borderColor = '#1B3A8C'}
                  onBlur={e => e.currentTarget.style.borderColor = '#e4e7ed'}>
                  <textarea
                    value={text}
                    onChange={e => { setText(e.target.value); autoResize(e.target); }}
                    onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
                    placeholder="Escribe un mensaje…"
                    rows={1}
                    style={{ width: '100%', background: 'none', border: 'none', outline: 'none', resize: 'none', fontFamily: 'inherit', fontSize: '.88rem', color: '#1a2232', maxHeight: 120, minHeight: 24, lineHeight: 1.5 }}
                  />
                </div>
                <button onClick={send} disabled={sending || !text.trim()} style={{
                  width: 40, height: 40, borderRadius: '50%', flexShrink: 0,
                  background: '#1B3A8C', color: '#fff', border: 'none',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  cursor: 'pointer', opacity: sending || !text.trim() ? 0.5 : 1, transition: 'all .18s',
                }}>
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" 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>
      </div>
    </div>
  );
}

export default function MensajesPage() {
  return (
    <>
      <Suspense><MensajesContent /></Suspense>
      <style>{`
        @media(max-width:767px){
          .thread-list{width:100%!important;min-width:0!important}
        }
      `}</style>
    </>
  );
}
