'use client';
import { Fragment, useEffect, useRef, useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import { Icon } from '@/lib/icons';
import { ProductPhoto } from '@/components/Photo';
import { useGo } from '@/lib/router';
import { sendMessage, markRead } from '@/lib/actions';
import type { Thread } from '@/lib/queries';

const QUICK = ['Toujours disponible ?', 'Oui, c’est négociable', 'Quel est votre dernier prix ?', 'On peut se voir où ?'];

export function Messenger({ threads, initialConvId }: { threads: Thread[]; initialConvId?: number }) {
  const { go } = useGo();
  const router = useRouter();
  const [list, setList] = useState<Thread[]>(threads);
  const [activeId, setActiveId] = useState<number | null>(initialConvId ?? null);
  const [draft, setDraft] = useState('');
  const [, startTransition] = useTransition();
  const scrollRef = useRef<HTMLDivElement>(null);

  // Server is the source of truth; a refresh (triggered globally by AuthProvider's
  // SSE stream, or by sending) re-seeds local state.
  useEffect(() => setList(threads), [threads]);

  // On desktop (two-pane), preselect the first conversation; on mobile, show the list first.
  useEffect(() => {
    if (
      activeId == null &&
      initialConvId == null &&
      threads.length &&
      typeof window !== 'undefined' &&
      window.matchMedia('(min-width: 880px)').matches
    ) {
      setActiveId(threads[0].id);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const active = list.find((c) => c.id === activeId) || null;

  useEffect(() => {
    if (active && scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [activeId, active?.messages.length]);

  const open = (id: number) => {
    setActiveId(id);
    setList((cs) => cs.map((c) => (c.id === id ? { ...c, unread: 0 } : c)));
    startTransition(async () => {
      await markRead(id);
      router.refresh();
    });
  };

  const send = (text?: string) => {
    const body = (text ?? draft).trim();
    if (!body || !active) return;
    const optimistic = { id: Date.now(), mine: true, body, at: 'maintenant' };
    setList((cs) =>
      cs.map((c) =>
        c.id === active.id ? { ...c, messages: [...c.messages, optimistic], preview: 'Vous : ' + body } : c
      )
    );
    setDraft('');
    startTransition(async () => {
      await sendMessage(active.id, body);
      router.refresh();
    });
  };

  if (list.length === 0) {
    return (
      <div className="msg-layout">
        <div className="thread" style={{ gridColumn: '1 / -1' }}>
          <div className="empty-thread">
            <Icon name="message" size={40} stroke={1.5} style={{ color: 'var(--faint)' }} />
            <h3 className="h3">Aucune conversation</h3>
            <p className="body" style={{ maxWidth: 300 }}>
              Contactez un vendeur depuis une annonce pour démarrer une discussion. Vos échanges apparaîtront ici.
            </p>
            <button className="btn btn-red" style={{ marginTop: 8 }} onClick={() => go('annonces')}>
              Parcourir les annonces
            </button>
          </div>
        </div>
      </div>
    );
  }

  let lastDay: string | undefined;

  return (
    <div className={'msg-layout ' + (active ? 'has-active' : '')}>
      <div className="conv-list">
        <div className="conv-search">
          <div className="input" style={{ padding: '10px 12px' }}>
            <Icon name="search" size={17} />
            <input placeholder="Rechercher une conversation" />
          </div>
        </div>
        <div className="conv-scroll">
          {list.map((c) => (
            <div key={c.id} className={'conv ' + (activeId === c.id ? 'on' : '')} onClick={() => open(c.id)}>
              <div className="conv-thumb"><ProductPhoto cat={c.adCat} icon={c.adIcon || undefined} h={48} radius={12} idx={c.id} /></div>
              <div className="conv-body">
                <div className="between"><span className="conv-name">{c.otherName}</span><span className="tiny" style={{ flexShrink: 0 }}>{c.time}</span></div>
                <div className="conv-prev">{c.preview}</div>
                <div className="tiny" style={{ marginTop: 3, color: 'var(--faint)' }}>{c.adTitle}</div>
              </div>
              {c.unread > 0 && <div className="conv-unread">{c.unread}</div>}
            </div>
          ))}
        </div>
      </div>

      {active ? (
        <div className="thread">
          <div className="thread-head">
            <button className="iconbtn msg-back" onClick={() => setActiveId(null)}><Icon name="arrowLeft" size={18} /></button>
            <div className="avatar" style={{ background: active.otherColor, width: 40, height: 40 }}>{active.otherInitial}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 700, fontSize: 15 }}>{active.otherName}</div>
              <div className="tiny row gap8" style={{ marginTop: 2 }}>
                <span style={{ width: 7, height: 7, borderRadius: 999, background: 'var(--teal)' }}></span>{active.role}
              </div>
            </div>
            <button className="iconbtn"><Icon name="phone" size={17} /></button>
            <button className="iconbtn" onClick={() => go('annonce', { id: active.adId })}><Icon name="info" size={17} /></button>
          </div>

          <div className="thread-ad">
            <div className="conv-thumb" style={{ width: 44, height: 44 }}><ProductPhoto cat={active.adCat} icon={active.adIcon || undefined} h={44} radius={10} idx={0} /></div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontWeight: 700, fontSize: 14, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{active.adTitle}</div>
              <div style={{ color: 'var(--red)', fontWeight: 700, fontSize: 14 }}>{active.adPrice} DA</div>
            </div>
            <button className="btn btn-ghost btn-sm" onClick={() => go('annonce', { id: active.adId })}>Voir l’annonce</button>
          </div>

          <div className="thread-scroll" ref={scrollRef}>
            {active.messages.length === 0 && (
              <div className="day-sep">Démarrez la conversation</div>
            )}
            {active.messages.map((m) => (
              <Fragment key={m.id}>
                <div className={'bubble ' + (m.mine ? 'me' : 'them')}>{m.body}</div>
                <div className={'bubble-time ' + (m.mine ? 'me' : 'them')}>{m.at}</div>
              </Fragment>
            ))}
          </div>

          <div className="quick-replies">
            {QUICK.map((q) => <div key={q} className="chip chip-sm" onClick={() => send(q)}>{q}</div>)}
          </div>
          <div className="composer">
            <button className="iconbtn" style={{ border: 'none' }}><Icon name="image" size={20} /></button>
            <input value={draft} onChange={(e) => setDraft(e.target.value)} placeholder="Écrivez un message…" onKeyDown={(e) => e.key === 'Enter' && send()} />
            <button className="msg-send" onClick={() => send()}><Icon name="arrowRight" size={20} stroke={2.4} /></button>
          </div>
        </div>
      ) : (
        <div className="thread">
          <div className="empty-thread">
            <Icon name="message" size={40} stroke={1.5} style={{ color: 'var(--faint)' }} />
            <h3 className="h3">Vos messages</h3>
            <p className="body" style={{ maxWidth: 280 }}>Sélectionnez une conversation pour échanger.</p>
          </div>
        </div>
      )}
    </div>
  );
}
