import React, { useEffect, useMemo, useRef, useState } from 'react';
import './Conversations.css';
import { apiGet, apiPost } from '../../services/apiClient';
import {
  ChatMeta,
  TAG_PRESETS,
  defaultMeta,
  ensureMetaForChats,
  getAllTags,
  loadMeta,
  saveMeta
} from '../../services/chatMeta';
import {
  assignChat,
  clearAttendance,
  finishChat,
  getAttendance,
  getEffectiveSeconds
} from '../../services/attendanceStore';
import { getCurrentUser, getCurrentUserId, getSectors, getUserById, getUsers } from '../../services/users';
import { getMessageAuthor, setMessageAuthor } from '../../services/messageAuthorStore';
import { getLastIncomingMessage, setLastIncomingMessage } from '../../services/incomingMessageStore';
import { logAuditEvent } from '../../services/auditApi';
import { clearAutoReply, getTemplates, sendTemplateMessage } from '../../services/templatesApi';
import ChatList from '../../components/chat/ChatList';
import ChatListItem from '../../components/chat/ChatListItem';
import ChatHeader from '../../components/chat/ChatHeader';
import ChatBubble from '../../components/chat/ChatBubble';
import ChatComposer from '../../components/chat/ChatComposer';
import ChatDetailsPanel from '../../components/chat/ChatDetailsPanel';

type ChatItem = {
  id: string;
  name: string;
  isGroup: boolean;
  unreadCount: number;
  timestamp: number | null;
  lastMessage: {
    body: string;
    fromMe: boolean;
    timestamp: number | null;
  } | null;
};

type ChatMessage = {
  id: string;
  body: string;
  fromMe: boolean;
  timestamp: number | null;
  author: string | null;
  type: string;
  media?: {
    url: string;
    type?: string;
    filename?: string;
    mimetype?: string;
  } | null;
};

const Conversations = () => {
  const [chats, setChats] = useState<ChatItem[]>([]);
  const [selectedChat, setSelectedChat] = useState<ChatItem | null>(null);
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [loadingChats, setLoadingChats] = useState(false);
  const [loadingMessages, setLoadingMessages] = useState(false);
  const [chatsError, setChatsError] = useState<string | null>(null);
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<ChatMeta['status'] | 'todos'>('todos');
  const [responsavelFilter, setResponsavelFilter] = useState('todos');
  const [unreadOnly, setUnreadOnly] = useState(false);
  const [tagFilter, setTagFilter] = useState('todos');
  const [queueFilter, setQueueFilter] = useState<'pendentes' | 'em_atendimento' | 'concluidos'>(
    'pendentes'
  );
  const [composerText, setComposerText] = useState('');
  const [showNewChat, setShowNewChat] = useState(false);
  const [newNumber, setNewNumber] = useState('');
  const [newMessage, setNewMessage] = useState('');
  const [tagInput, setTagInput] = useState('');
  const [meta, setMeta] = useState<Record<string, ChatMeta>>(() => loadMeta());
  const fallbackUserId = getUsers()[0]?.id || 'u1';
  const [currentUserId] = useState(getCurrentUserId() || fallbackUserId);
  const [tick, setTick] = useState(0);
  const [showDetails, setShowDetails] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement | null>(null);
  const availableTags = useMemo(() => getAllTags(meta), [meta]);

  useEffect(() => {
    loadChats();
  }, []);

  useEffect(() => {
    const timer = setInterval(() => {
      loadChats(true);
    }, 5000);
    return () => clearInterval(timer);
  }, []);

  useEffect(() => {
    const timer = setInterval(() => setTick(prev => prev + 1), 1000);
    return () => clearInterval(timer);
  }, []);

  useEffect(() => {
    if (!selectedChat) return;
    requestAnimationFrame(() => {
      messagesEndRef.current?.scrollIntoView({ behavior: 'auto', block: 'end' });
    });
  }, [selectedChat, messages]);

  const loadChats = async (silent = false) => {
    if (!silent) {
      setLoadingChats(true);
    }
    setChatsError(null);
    try {
      const data = await apiGet('/chats', 45000);
      setChats(data);
      const chatIds = data.map((chat: ChatItem) => chat.id);
      const ensured = ensureMetaForChats(meta, chatIds);
      let nextMeta = ensured.meta;
      let metaChanged = ensured.changed;

      data.forEach((chat: ChatItem) => {
        const lastMessage = chat.lastMessage;
        const incomingTimestamp = lastMessage?.fromMe === false
          ? lastMessage?.timestamp || chat.timestamp
          : null;

        if (!incomingTimestamp) return;

        const lastSeen = getLastIncomingMessage(chat.id);
        if (lastSeen && incomingTimestamp <= lastSeen) return;

        setLastIncomingMessage(chat.id, incomingTimestamp);

        const attendance = getAttendance(chat.id);
        if (attendance && !attendance.active) {
          clearAttendance(chat.id);
          const metaItem = nextMeta[chat.id] || defaultMeta();
          if (metaItem.status === 'concluido') {
            nextMeta = {
              ...nextMeta,
              [chat.id]: {
                ...metaItem,
                status: 'em_andamento',
                responsavel: 'Sem setor'
              }
            };
            metaChanged = true;
          }
        }
      });

      if (metaChanged) {
        setMeta(nextMeta);
        saveMeta(nextMeta);
      }
      return data as ChatItem[];
    } catch (error) {
      console.error('Erro ao carregar chats:', error);
      setChatsError(error.message);
      if (!silent) {
        alert(error.message);
      }
    } finally {
      if (!silent) {
        setLoadingChats(false);
      }
    }
    return null;
  };

  const refreshMessages = async (chat: ChatItem, silent = false) => {
    if (!silent) {
      setLoadingMessages(true);
    }
    try {
      const data = await apiGet(`/chats/${chat.id}/messages?limit=50`);
      setMessages(data);
    } catch (error) {
      console.error('Erro ao carregar mensagens:', error);
      if (!silent) {
        alert(error.message);
      }
    } finally {
      if (!silent) {
        setLoadingMessages(false);
      }
    }
  };

  useEffect(() => {
    if (!selectedChat) return;
    const timer = setInterval(() => {
      refreshMessages(selectedChat, true);
    }, 5000);
    return () => clearInterval(timer);
  }, [selectedChat]);

  const selectChat = async (chat: ChatItem) => {
    setSelectedChat(chat);
    setComposerText('');
    setShowDetails(false);
    await refreshMessages(chat, false);
  };

  const handleSend = async () => {
    if (!selectedChat || !composerText.trim()) return;
    try {
      const messageText = composerText.trim();
      const result = await apiPost(`/chats/${selectedChat.id}/enviar-mensagem`, {
        mensagem: messageText
      });
      const messageId =
        result?.result?.id?._serialized ||
        result?.result?.id?.id ||
        result?.result?.id;
      if (messageId) {
        setMessageAuthor(selectedChat.id, String(messageId), currentUserId);
      }
      logAuditEvent('message_sent', {
        userId: currentUserId,
        userName: currentUser?.name || null,
        details: {
          chatId: selectedChat.id,
          chatName: selectedChat.name,
          message: messageText.slice(0, 200)
        }
      }).catch(() => {});
      setComposerText('');
      selectChat(selectedChat);
    } catch (error) {
      console.error('Erro ao enviar mensagem:', error);
      alert('Erro: ' + error.message);
    }
  };

  const handleSendMedia = async (file: File) => {
    if (!selectedChat) return;
    try {
      const maxSize = 20 * 1024 * 1024;
      if (file.size > maxSize) {
        alert('Arquivo muito grande (max 20MB).');
        return;
      }
      const isImage = file.type.startsWith('image/');
      if (isImage) {
        const resized = await resizeImage(file, 1600, 0.8);
        await apiPost(`/chats/${selectedChat.id}/enviar-midia`, {
          data: resized.data,
          mimetype: resized.mimetype,
          filename: resized.filename
        });
      } else {
        const reader = new FileReader();
        reader.onload = async () => {
          const result = String(reader.result || '');
          const base64 = result.includes(',') ? result.split(',')[1] : result;
          await apiPost(`/chats/${selectedChat.id}/enviar-midia`, {
            data: base64,
            mimetype: file.type,
            filename: file.name
          });
          selectChat(selectedChat);
        };
        reader.readAsDataURL(file);
        return;
      }
      selectChat(selectedChat);
    } catch (error) {
      console.error('Erro ao enviar midia:', error);
      const message = error instanceof Error ? error.message : 'Erro ao enviar midia.';
      alert(message);
    }
  };

  const resizeImage = (file: File, maxSizePx: number, quality: number) => {
    return new Promise<{ data: string; mimetype: string; filename: string }>((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => {
        const img = new Image();
        img.onload = () => {
          const scale = Math.min(1, maxSizePx / Math.max(img.width, img.height));
          const canvas = document.createElement('canvas');
          canvas.width = Math.round(img.width * scale);
          canvas.height = Math.round(img.height * scale);
          const ctx = canvas.getContext('2d');
          if (!ctx) {
            reject(new Error('Canvas indisponivel'));
            return;
          }
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          const outputType = 'image/jpeg';
          const dataUrl = canvas.toDataURL(outputType, quality);
          const base64 = dataUrl.split(',')[1];
          resolve({
            data: base64,
            mimetype: outputType,
            filename: file.name.replace(/\.[^.]+$/, '') + '.jpg'
          });
        };
        img.onerror = () => reject(new Error('Imagem invalida'));
        img.src = String(reader.result);
      };
      reader.onerror = () => reject(new Error('Erro ao ler arquivo'));
      reader.readAsDataURL(file);
    });
  };

  const handleStartChat = async () => {
    if (!newNumber.trim() || !newMessage.trim()) {
      alert('Preencha numero e mensagem');
      return;
    }
    try {
      const messageText = newMessage.trim();
      const result = await apiPost('/chats/iniciar', {
        numero: newNumber,
        mensagem: messageText
      });
      setNewNumber('');
      setNewMessage('');
      setShowNewChat(false);
      logAuditEvent('message_sent', {
        userId: currentUserId,
        userName: currentUser?.name || null,
        details: {
          chatId: newNumber.trim(),
          chatName: newNumber.trim(),
          message: messageText.slice(0, 200)
        }
      }).catch(() => {});
      const updated = await loadChats();
      const created = result.chatId && updated
        ? updated.find(c => c.id === result.chatId)
        : null;
      if (created) {
        selectChat(created);
      }
    } catch (error) {
      console.error('Erro ao iniciar conversa:', error);
      alert('Erro: ' + error.message);
    }
  };

  const baseFilteredChats = useMemo(() => {
    const term = search.trim().toLowerCase();
    return chats.filter(chat => {
      if (chat.isGroup) return false;
      const attendance = getAttendance(chat.id);
      const isActive = attendance?.active;
      const isFinished = attendance && !attendance.active && attendance.finishedAt;
      const isPending = !attendance;
      if (queueFilter === 'pendentes' && !isPending) return false;
      if (queueFilter === 'em_atendimento' && !isActive) return false;
      if (queueFilter === 'concluidos' && !isFinished) return false;
      const metaItem = meta[chat.id] || defaultMeta();
      if (term && !chat.name.toLowerCase().includes(term)) return false;
      if (statusFilter !== 'todos' && metaItem.status !== statusFilter) return false;
      if (responsavelFilter !== 'todos' && metaItem.responsavel !== responsavelFilter) return false;
      if (unreadOnly && chat.unreadCount === 0) return false;
      return true;
    });
  }, [chats, meta, search, statusFilter, responsavelFilter, unreadOnly, queueFilter]);

  const filteredChats = useMemo(() => {
    if (tagFilter === 'todos') return baseFilteredChats;
    return baseFilteredChats.filter(chat => {
      const metaItem = meta[chat.id] || defaultMeta();
      return metaItem.tags.includes(tagFilter);
    });
  }, [baseFilteredChats, meta, tagFilter]);

  const tagStats = useMemo(() => {
    const counts: Record<string, number> = {};
    baseFilteredChats.forEach(chat => {
      const metaItem = meta[chat.id] || defaultMeta();
      metaItem.tags.forEach(tag => {
        counts[tag] = (counts[tag] || 0) + 1;
      });
    });
    return Object.entries(counts)
      .map(([tag, count]) => ({ tag, count }))
      .sort((a, b) => (b.count === a.count ? a.tag.localeCompare(b.tag) : b.count - a.count));
  }, [baseFilteredChats, meta]);

  const queueCounts = useMemo(() => {
    return chats.reduce(
      (acc, chat) => {
        if (chat.isGroup) return acc;
        const attendance = getAttendance(chat.id);
        if (!attendance) {
          acc.pendentes += 1;
        } else if (attendance.active) {
          acc.em_atendimento += 1;
        } else if (attendance.finishedAt) {
          acc.concluidos += 1;
        }
        return acc;
      },
      { pendentes: 0, em_atendimento: 0, concluidos: 0 }
    );
  }, [chats, tick]);

  const chatMeta = selectedChat ? meta[selectedChat.id] || defaultMeta() : defaultMeta();
  const attendance = selectedChat ? getAttendance(selectedChat.id) : null;
  const attendanceSeconds = attendance ? getEffectiveSeconds(attendance) : 0;
  const currentUser = getCurrentUser() || getUserById(currentUserId);
  const attendanceUser = attendance ? getUserById(attendance.userId) : currentUser;

  const updateMeta = (chatId: string, patch: Partial<ChatMeta>) => {
    const current = meta[chatId] || defaultMeta();
    const next = { ...meta, [chatId]: { ...current, ...patch } };
    setMeta(next);
    saveMeta(next);
  };

  const addTagValue = (value: string) => {
    if (!selectedChat) return;
    const trimmed = value.trim();
    if (!trimmed) return;
    const current = meta[selectedChat.id] || defaultMeta();
    if (current.tags.includes(trimmed)) {
      setTagInput('');
      return;
    }
    updateMeta(selectedChat.id, { tags: [...current.tags, trimmed] });
    setTagInput('');
  };

  const addTag = () => {
    addTagValue(tagInput);
  };

  const removeTag = (tag: string) => {
    if (!selectedChat) return;
    const current = meta[selectedChat.id] || defaultMeta();
    updateMeta(selectedChat.id, { tags: current.tags.filter(t => t !== tag) });
  };

  const handleAssign = () => {
    if (!selectedChat) return;
    const currentAttendance = getAttendance(selectedChat.id);
    if (currentAttendance?.active) {
      return;
    }
    assignChat(selectedChat.id, currentUserId);
    updateMeta(selectedChat.id, { status: 'em_andamento', responsavel: currentUser.sector });
    logAuditEvent('attendance_assigned', {
      userId: currentUserId,
      userName: currentUser?.name || null,
      details: { chatId: selectedChat.id, chatName: selectedChat.name }
    }).catch(() => {});
    sendAssignmentMessage(selectedChat.id, selectedChat.name);
    setTick(prev => prev + 1);
  };

  const handleFinish = async () => {
    if (!selectedChat) return;
    const currentAttendance = getAttendance(selectedChat.id);
    const ok = await finishChat(selectedChat.id, currentUserId);
    if (!ok) {
      alert('Nenhum atendimento ativo para finalizar.');
      return;
    }
    updateMeta(selectedChat.id, { status: 'concluido' });
    logAuditEvent('attendance_finished', {
      userId: currentUserId,
      userName: currentUser?.name || null,
      details: { chatId: selectedChat.id, chatName: selectedChat.name }
    }).catch(() => {});
    sendFinishMessage(selectedChat.id, selectedChat.name);
    clearAutoReply(selectedChat.id).catch(() => {});
    setTick(prev => prev + 1);
  };

  const handleTransfer = () => {
    if (!selectedChat) return;
    updateMeta(selectedChat.id, { status: 'transferido' });
    logAuditEvent('attendance_transfer', {
      userId: currentUserId,
      userName: currentUser?.name || null,
      details: { chatId: selectedChat.id, chatName: selectedChat.name }
    }).catch(() => {});
  };

  const applyTemplateText = (content: string, values: Record<string, string>) => {
    return content.replace(/{{\s*([a-zA-Z0-9_.-]+)\s*}}/g, (_, key) => {
      return values[key] || '';
    });
  };

  const sendAssignmentMessage = async (chatId: string, chatName: string) => {
    try {
      const userName = currentUser?.name || 'Atendente';
      const vars = { nome: chatName || '', atendente: userName };
      const result = await sendTemplateMessage(chatId, { type: 'onAssign', vars });
      if (result?.error) {
        throw new Error(result.error);
      }
      logAuditEvent('message_sent', {
        userId: currentUserId,
        userName: currentUser?.name || null,
        details: {
          chatId,
          chatName,
          message: '[template onAssign]'
        }
      }).catch(() => {});
    } catch (error) {
      try {
        const templates = await getTemplates();
        const template = templates.find((item) => item.onAssign);
        const userName = currentUser?.name || 'Atendente';
        const message = template?.content
          ? applyTemplateText(template.content, {
              nome: chatName || '',
              atendente: userName
            }).trim()
          : `Atendimento iniciado por ${userName}.`;
        if (!message) return;
        await apiPost(`/chats/${chatId}/enviar-mensagem`, { mensagem: message });
      } catch (fallbackError) {
        console.error('Erro ao enviar mensagem de atendimento:', fallbackError);
      }
    }
  };

  const sendFinishMessage = async (chatId: string, chatName: string) => {
    try {
      const templates = await getTemplates();
      const template = templates.find((item) => item.onFinish);
      const userName = currentUser?.name || 'Atendente';
      const message = template?.content
        ? applyTemplateText(template.content, {
            nome: chatName || '',
            atendente: userName
          }).trim()
        : `Atendimento finalizado por ${userName}.`;
      if (!message) return;
      await apiPost(`/chats/${chatId}/enviar-mensagem`, { mensagem: message });
      logAuditEvent('message_sent', {
        userId: currentUserId,
        userName: currentUser?.name || null,
        details: {
          chatId,
          chatName,
          message: message.slice(0, 200)
        }
      }).catch(() => {});
    } catch (error) {
      console.error('Erro ao enviar mensagem de encerramento:', error);
    }
  };

  const formatTime = (timestamp: number | null) => {
    if (!timestamp) return '';
    const date = new Date(timestamp * 1000);
    return date.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' });
  };

  const formatDuration = (seconds: number) => {
    const h = Math.floor(seconds / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    const s = seconds % 60;
    return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}:${s
      .toString()
      .padStart(2, '0')}`;
  };

  const formatDateTime = (timestamp: number | null) => {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    return date.toLocaleString('pt-BR', { hour: '2-digit', minute: '2-digit' });
  };

  return (
    <div className={`conversations ${showDetails ? 'details-open' : ''}`}>
      <ChatList title="Conversas" onRefresh={loadChats}>
        <div className="sidebar-actions">
          <input
            type="text"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            placeholder="Buscar atendimento..."
            className="search-input"
          />
          <div className="queue-tabs">
            <button
              className={`queue-tab ${queueFilter === 'pendentes' ? 'active' : ''}`}
              onClick={() => setQueueFilter('pendentes')}
            >
              Pendentes ({queueCounts.pendentes})
            </button>
            <button
              className={`queue-tab ${queueFilter === 'em_atendimento' ? 'active' : ''}`}
              onClick={() => setQueueFilter('em_atendimento')}
            >
              Em atendimento ({queueCounts.em_atendimento})
            </button>
            <button
              className={`queue-tab ${queueFilter === 'concluidos' ? 'active' : ''}`}
              onClick={() => setQueueFilter('concluidos')}
            >
              Concluidos ({queueCounts.concluidos})
            </button>
          </div>
          <div className="filters-row">
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value as ChatMeta['status'] | 'todos')}
              className="select filter"
            >
              <option value="todos">Todos</option>
              <option value="em_andamento">Em andamento</option>
              <option value="transferido">Transferido</option>
              <option value="concluido">Concluido</option>
            </select>
            <select
              value={responsavelFilter}
              onChange={(e) => setResponsavelFilter(e.target.value)}
              className="select filter"
            >
              <option value="todos">Atendente</option>
              <option value="Sem setor">Sem setor</option>
              {getSectors().map(sector => (
                <option key={sector} value={sector}>
                  {sector}
                </option>
              ))}
            </select>
            <select
              value={tagFilter}
              onChange={(e) => setTagFilter(e.target.value)}
              className="select filter"
            >
              <option value="todos">Tag</option>
              {availableTags.map(tag => (
                <option key={tag} value={tag}>
                  {tag}
                </option>
              ))}
            </select>
            <label className="toggle">
              <input
                type="checkbox"
                checked={unreadOnly}
                onChange={(e) => setUnreadOnly(e.target.checked)}
              />
              <span>Nao lidas</span>
            </label>
          </div>
          <button className="primary-btn" onClick={() => setShowNewChat(!showNewChat)}>
            Nova conversa
          </button>
        </div>
        {tagStats.length > 0 && (
          <div className="tag-filter-list">
            <button
              className={`tag-chip ${tagFilter === 'todos' ? 'active' : ''}`}
              onClick={() => setTagFilter('todos')}
            >
              Todas
            </button>
            {tagStats.map(item => (
              <button
                key={item.tag}
                className={`tag-chip ${tagFilter === item.tag ? 'active' : ''}`}
                onClick={() => setTagFilter(item.tag)}
                title={`Filtrar por ${item.tag}`}
              >
                {item.tag}
                <span className="tag-count">{item.count}</span>
              </button>
            ))}
          </div>
        )}

        {showNewChat && (
          <div className="new-chat-card">
            <input
              type="text"
              value={newNumber}
              onChange={(e) => setNewNumber(e.target.value)}
              placeholder="Numero (5511...)"
              className="input"
            />
            <textarea
              value={newMessage}
              onChange={(e) => setNewMessage(e.target.value)}
              placeholder="Mensagem inicial"
              rows={3}
              className="input textarea"
            />
            <div className="new-chat-actions">
              <button className="primary-btn" onClick={handleStartChat}>
                Iniciar
              </button>
              <button className="ghost-btn" onClick={() => setShowNewChat(false)}>
                Cancelar
              </button>
            </div>
          </div>
        )}

        <div className="chat-list-wrap">
          <div className="chat-list">
            {loadingChats ? (
              <div className="loading">Carregando conversas...</div>
            ) : chatsError ? (
              <div className="loading">{chatsError}</div>
            ) : filteredChats.length === 0 ? (
              <div className="loading">Nenhuma conversa encontrada.</div>
            ) : (
              filteredChats.map(chat => {
                const metaItem = meta[chat.id] || defaultMeta();
                const attendance = getAttendance(chat.id);
                const attendantUser = attendance ? getUserById(attendance.userId) : null;
                const queueTag = !attendance
                  ? 'pendente'
                  : attendance.active
                    ? 'em_atendimento'
                    : 'concluido';
                return (
                  <ChatListItem
                    key={chat.id}
                    active={selectedChat?.id === chat.id}
                    title={chat.name}
                    preview={chat.lastMessage?.body || 'Sem mensagens'}
                    time={formatTime(chat.timestamp)}
                    avatarText={chat.name ? chat.name.charAt(0).toUpperCase() : '?'}
                    onClick={() => selectChat(chat)}
                    tags={
                      <>
                        <span className={`tag queue ${queueTag}`}>{queueTag.replace('_', ' ')}</span>
                        {attendantUser && (
                          <span className="tag attendant">
                            <span
                              className="agent-dot"
                              style={{ background: attendantUser.color }}
                            ></span>
                            {attendantUser.name}
                          </span>
                        )}
                        {metaItem.tags.map(tag => (
                          <span key={tag} className="tag">
                            {tag}
                          </span>
                        ))}
                      </>
                    }
                  />
                );
              })
            )}
          </div>
        </div>
      </ChatList>

      <section className="conversation-panel">
        {selectedChat ? (
          <>
            <ChatHeader
              title={selectedChat.name}
              subtitle="Contato"
              avatarText={selectedChat.name ? selectedChat.name.charAt(0).toUpperCase() : '?'}
              onProfileClick={() => setShowDetails((prev) => !prev)}
              actions={
                <>
                  <div className="select attendant-pill">{attendanceUser.sector}</div>
                  <select
                    value={chatMeta.status}
                    onChange={(e) =>
                      updateMeta(selectedChat.id, { status: e.target.value as ChatMeta['status'] })
                    }
                    className="select"
                  >
                    <option value="em_andamento">Em andamento</option>
                    <option value="transferido">Transferido</option>
                    <option value="concluido">Concluido</option>
                  </select>
                  {!(attendance?.active && attendance.userId === currentUserId) && (
                    <button className="ghost-btn" onClick={handleAssign}>
                      Pegar
                    </button>
                  )}
                  <button
                    className="ghost-btn"
                    onClick={handleTransfer}
                  >
                    Transferir
                  </button>
                  {attendance?.active && (
                    <button className="primary-btn" onClick={handleFinish}>
                      Concluir
                    </button>
                  )}
                </>
              }
            />

            <div className="conversation-tags">
            <div className="tag-list">
                <span className="tag">{currentUser.name}</span>
                <span className="tag">{attendance ? 'Em atendimento' : 'Nao iniciado'}</span>
                <span className="tag">{formatDuration(attendanceSeconds)}</span>
                {attendance?.finishedAt && (
                  <span className="tag">Concluido - {formatDateTime(attendance.finishedAt)}</span>
                )}
                {chatMeta.tags.map(tag => (
                  <button key={tag} className="tag removable" onClick={() => removeTag(tag)}>
                    {tag} <span>x</span>
                  </button>
                ))}
              </div>
              <div className="tag-input">
                <input
                  type="text"
                  value={tagInput}
                  onChange={(e) => setTagInput(e.target.value)}
                  placeholder="Adicionar tag"
                />
                <button className="ghost-btn" onClick={addTag}>
                  Adicionar
                </button>
              </div>
            </div>
            <div className="tag-presets">
              {TAG_PRESETS.map(tag => (
                <button key={tag} className="tag preset" onClick={() => addTagValue(tag)}>
                  {tag}
                </button>
              ))}
            </div>

            <div className="conversation-body whatsapp-wallpaper">
              {loadingMessages ? (
                <div className="loading">Carregando mensagens...</div>
              ) : (
                messages.map((msg) => {
                  const authorId = msg.fromMe
                    ? getMessageAuthor(selectedChat.id, msg.id) || attendanceUser.id
                    : null;
                  const authorUser = authorId ? getUserById(authorId) : null;
                  return (
                    <ChatBubble
                      key={msg.id}
                      fromMe={msg.fromMe}
                      author={msg.fromMe ? authorUser?.name || attendanceUser.name : null}
                      authorColor={authorUser?.color || attendanceUser.color}
                      text={msg.body || (msg.media ? '' : '[midia]')}
                      media={msg.media || null}
                      time={formatTime(msg.timestamp)}
                    />
                  );
                })
              )}
              <div ref={messagesEndRef} />
            </div>

            <ChatComposer
              value={composerText}
              onChange={setComposerText}
              onSend={handleSend}
              onSendMedia={handleSendMedia}
            />
          </>
        ) : (
          <div className="empty-state">
            <h3>Selecione uma conversa</h3>
            <p>Abra uma conversa ao lado para visualizar as mensagens.</p>
          </div>
        )}
      </section>

      {showDetails && (
        <ChatDetailsPanel
          title={selectedChat?.name || 'Detalhes'}
          subtitle={selectedChat ? 'Contato ativo' : 'Selecione uma conversa'}
          avatarText={selectedChat?.name ? selectedChat.name.charAt(0).toUpperCase() : '?'}
          notes="Use este painel para adicionar informacoes importantes sobre o contato."
        />
      )}
    </div>
  );
};

export default Conversations;
