'use client';

import { useState, useEffect, useRef } from 'react';
import { Conversation } from '@/lib/db';

interface ConversationListProps {
  onSelect: (convo: Conversation) => void;
  selectedId: number | null;
}

/* ── Relative time short ── */
function shortTime(unixSeconds: number): string {
  const now = Date.now() / 1000;
  const diff = now - unixSeconds;
  if (diff < 60) return 'ahora';
  if (diff < 3600) return `${Math.floor(diff / 60)}m`;
  if (diff < 86400) return new Date(unixSeconds * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  if (diff < 604800) {
    return ['Dom','Lun','Mar','Mié','Jue','Vie','Sáb'][new Date(unixSeconds * 1000).getDay()];
  }
  return new Date(unixSeconds * 1000).toLocaleDateString([], { day: 'numeric', month: 'short' });
}

/* ── Avatar Helpers ── */
const AVATAR_COLORS: [string, string][] = [
  ['#10b981', '#0d9488'],
  ['#8b5cf6', '#7c3aed'],
  ['#3b82f6', '#2563eb'],
  ['#f43f5e', '#e11d48'],
  ['#f59e0b', '#d97706'],
  ['#6366f1', '#4f46e5'],
  ['#ec4899', '#db2777'],
  ['#14b8a6', '#0f766e'],
];

function getAvatarGradient(name: string): string {
  let hash = 0;
  for (let i = 0; i < name.length; i++) hash = name.charCodeAt(i) + ((hash << 5) - hash);
  const [a, b] = AVATAR_COLORS[Math.abs(hash) % AVATAR_COLORS.length];
  return `linear-gradient(135deg, ${a}, ${b})`;
}

function getInitials(name: string): string {
  return name
    .split(' ')
    .filter(Boolean)
    .map((w) => w[0])
    .join('')
    .toUpperCase()
    .slice(0, 2);
}

/* ── Skeleton Row ── */
function SkeletonRow() {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '12px', padding: '11px 12px' }}>
      <div className="skeleton" style={{ width: '48px', height: '48px', borderRadius: '12px', flexShrink: 0 }} />
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: '8px' }}>
        <div className="skeleton" style={{ height: '13px', width: '110px', borderRadius: '6px' }} />
        <div className="skeleton" style={{ height: '11px', width: '160px', borderRadius: '6px' }} />
      </div>
    </div>
  );
}

export function ConversationList({ onSelect, selectedId }: ConversationListProps) {
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [activeFilter, setActiveFilter] = useState<'all' | 'ai' | 'human' | 'unread'>('all');
  // Track last_message_at when user opens each conversation — used for unread dots
  const seenAt = useRef<Map<number, number>>(new Map());
  const [, forceUpdate] = useState(0);

  const fetchConversations = async () => {
    try {
      const res = await fetch('/api/conversations');
      const data = await res.json();

      // Solo marcar como "visto" si seenAt está vacío (primera carga)
      const isFirstLoad = !seenAt.current.size;

      setConversations(data);

      if (isFirstLoad) {
        data.forEach((c: Conversation) => {
          seenAt.current.set(c.id, c.last_message_at || 0);
        });
      }
    } catch (err) {
      console.error('Error fetching conversations:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchConversations();
    const interval = setInterval(fetchConversations, 2000);
    return () => clearInterval(interval);
  }, []);

  /* ── Filter ── */
  const filtered = conversations.filter((c) => {
    if (search.trim()) {
      const s = search.toLowerCase();
      const nameMatch = c.name?.toLowerCase().includes(s);
      const phoneMatch = c.phone.includes(s);
      if (!nameMatch && !phoneMatch) return false;
    }
    if (activeFilter === 'ai') return c.mode === 'AI';
    if (activeFilter === 'human') return c.mode === 'HUMAN';
    if (activeFilter === 'unread') {
      const lastSeen = seenAt.current.get(c.id) ?? 0;
      return c.last_message_at && lastSeen < c.last_message_at;
    }
    return true;
  });

  /* ── Skeleton Loading ── */
  if (loading && conversations.length === 0) {
    return (
      <>
        <div className="sidebar-top">
          <h2>Bandeja <span className="badge-count">0</span></h2>
          <div className="search-epic">
            <svg fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24"><path strokeLinecap="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
            <input type="search" placeholder="Buscar…" disabled />
          </div>
        </div>
        <div className="convo-scroll" style={{ opacity: 0.5 }}>
          {[1, 2, 3, 4, 5].map((i) => (
            <SkeletonRow key={i} />
          ))}
        </div>
      </>
    );
  }

  return (
    <>
      {/* Header + Search */}
      <div className="sidebar-top">
        <h2>
          Bandeja <span className="badge-count" id="chatCount">{conversations.length}</span>
        </h2>
        <div className="search-epic">
          <svg fill="none" stroke="currentColor" strokeWidth="2" viewBox="0 0 24 24">
            <path strokeLinecap="round" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          <input
            type="search"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Buscar… (Ctrl+K)"
          />
        </div>
        <div className="filters">
          <button
            type="button"
            className={`filter ${activeFilter === 'all' ? 'active' : ''}`}
            onClick={() => setActiveFilter('all')}
          >
            Todos
          </button>
          <button
            type="button"
            className={`filter ${activeFilter === 'ai' ? 'active' : ''}`}
            onClick={() => setActiveFilter('ai')}
          >
            IA
          </button>
          <button
            type="button"
            className={`filter ${activeFilter === 'human' ? 'active' : ''}`}
            onClick={() => setActiveFilter('human')}
          >
            Humano
          </button>
          <button
            type="button"
            className={`filter ${activeFilter === 'unread' ? 'active' : ''}`}
            onClick={() => setActiveFilter('unread')}
          >
            No leídos
          </button>
        </div>
      </div>

      {/* Conversation Items */}
      <div className="convo-scroll" id="convoList">
        {filtered.length === 0 ? (
          <div className="p-8 text-center animate-fade-in" style={{ color: 'var(--text-muted)' }}>
            <p className="text-xs font-semibold">
              {search ? 'Sin resultados' : 'No hay conversaciones'}
            </p>
          </div>
        ) : (
          filtered.map((convo) => {
            const displayName = convo.name || convo.phone.split('@')[0];
            const isSelected = selectedId === convo.id;
            const hasUnread = convo.last_message_at && (seenAt.current.get(convo.id) ?? 0) < convo.last_message_at;

            return (
              <div
                key={convo.id}
                onClick={() => {
                  seenAt.current.set(convo.id, convo.last_message_at || 0);
                  forceUpdate((n) => n + 1);
                  onSelect(convo);
                }}
                className={`convo ${isSelected ? 'active' : ''}`}
              >
                <div
                  className="avatar"
                  style={{
                    background: getAvatarGradient(displayName),
                    width: '48px',
                    height: '48px',
                  }}
                >
                  {getInitials(displayName)}
                  <span className={`mode-pip ${convo.mode === 'AI' ? 'ai' : 'human'}`}>
                    {convo.mode === 'AI' ? 'IA' : 'H'}
                  </span>
                </div>

                <div className="convo-info">
                  <div className="convo-row">
                    <span className="convo-name">{displayName}</span>
                    <span className="convo-time">
                      {convo.last_message_at ? shortTime(convo.last_message_at) : ''}
                    </span>
                  </div>
                  <div className="convo-row">
                    <span className="convo-preview">
                      {convo.last_message_preview || 'Sin mensajes'}
                    </span>
                    {!isSelected && hasUnread && (
                      <span className="unread-pill">1</span>
                    )}
                  </div>
                </div>
              </div>
            );
          })
        )}
      </div>
    </>
  );
}
