import { useEffect, useState, useRef } from 'react';
import { Link } from 'react-router-dom';
import { RenewalModal } from '../components/RenewalModal';
import { Layout } from '../components/Layout';
import { VariableSelector } from '../components/VariableSelector';
import { ConfirmDialog } from '../components/ConfirmDialog';
import { toast } from '../components/Toast';
import { Lock, Unlock, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, MoreVertical, X } from 'lucide-react';
import api from '../lib/api';
import { DatePicker } from '../components/DatePicker';

interface Client {
  id: number;
  name: string;
  username?: string;
  password?: string;
  whatsapp?: string;
  valor_mensalidade: number;
  status: 'active' | 'inactive' | 'suspended' | 'expired';
  expires_at?: string;
  server: {
    id: number;
    name: string;
  };
}


interface Server {
  id: number;
  name: string;
}

interface Connection {
  id: number;
  instance_name: string;
  phone_number: string | null;
  status: 'disconnected' | 'connecting' | 'connected' | 'error';
}

interface WhatsAppMessage {
  id: string;
  title: string;
  content: string;
}

const messageTemplates: WhatsAppMessage[] = [
  {
    id: 'expiring',
    title: 'Aviso de Vencimento',
    content: 'Olá {nome}! Seu plano no servidor {servidor} vence em breve.\n\n📱 Usuário: {usuario}\n🔐 Senha: {senha}\n💰 Valor: R$ {valor}\n📅 Vencimento: {vencimento}'
  },
  {
    id: 'expired',
    title: 'Plano Vencido',
    content: 'Olá {nome}, seu plano no servidor {servidor} venceu. Renove agora por R$ {valor} para continuar aproveitando.\n\n📱 Usuário: {usuario}\n🔐 Senha: {senha}'
  },
  {
    id: 'renewed',
    title: 'Renovação Confirmada',
    content: 'Olá {nome}! Seu plano no servidor {servidor} foi renovado com sucesso.\n\n📱 Usuário: {usuario}\n🔐 Senha: {senha}\n💰 Valor: R$ {valor}\n📅 Novo vencimento: {vencimento}'
  },
  {
    id: 'custom',
    title: 'Mensagem Personalizada',
    content: ''
  }
];

// Helper function to format expiration date
const formatExpirationDate = (expiresAt: string | null | undefined): string => {
  if (!expiresAt) return '-';
  
  try {
    // Handle different date formats from backend
    let dateStr = expiresAt;
    
    // If it's just a date string (YYYY-MM-DD), parse it as local date
    // This prevents timezone issues where UTC date becomes previous day in local time
    if (dateStr.match(/^\d{4}-\d{2}-\d{2}$/)) {
      const [year, month, day] = dateStr.split('-').map(Number);
      // Create date in local timezone (not UTC)
      const date = new Date(year, month - 1, day);
      return isNaN(date.getTime()) ? '-' : date.toLocaleDateString('pt-BR');
    }
    
    // If it's already a full ISO string, check if it has time component
    if (dateStr.includes('T')) {
      // Extract just the date part if it's a full datetime
      const datePart = dateStr.split('T')[0];
      if (datePart.match(/^\d{4}-\d{2}-\d{2}$/)) {
        const [year, month, day] = datePart.split('-').map(Number);
        const date = new Date(year, month - 1, day);
        return isNaN(date.getTime()) ? '-' : date.toLocaleDateString('pt-BR');
      }
      // If it's a full datetime, parse normally
      const date = new Date(dateStr);
      return isNaN(date.getTime()) ? '-' : date.toLocaleDateString('pt-BR');
    }
    
    // Try parsing as-is
    const date = new Date(dateStr);
    return isNaN(date.getTime()) ? '-' : date.toLocaleDateString('pt-BR');
  } catch {
    return '-';
  }
};

export function ClientsPage() {
  const [clients, setClients] = useState<Client[]>([]);
  const [servers, setServers] = useState<Server[]>([]);
  const [loading, setLoading] = useState(true);
  const [loadingClients, setLoadingClients] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [debouncedSearchTerm, setDebouncedSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [serverFilter, setServerFilter] = useState<string>('');
  const [expiresFromFilter, setExpiresFromFilter] = useState<string>('');
  const [expiresToFilter, setExpiresToFilter] = useState<string>('');
  const [sortBy, setSortBy] = useState<string>('expires_at');
  const [sortDir, setSortDir] = useState<'asc' | 'desc'>('asc');
  const [currentPage, setCurrentPage] = useState(1);
  const [perPage, setPerPage] = useState(50);
  const [pagination, setPagination] = useState<{ current_page: number; last_page: number; per_page: number; total: number; from: number; to: number } | null>(null);
  const [renewalClient, setRenewalClient] = useState<{ id: number; name: string } | null>(null);
  const [whatsappModal, setWhatsappModal] = useState<Client | null>(null);
  const [bulkWhatsappModal, setBulkWhatsappModal] = useState<boolean>(false);
  const [editClient, setEditClient] = useState<Client | null>(null);
  const [selectedTemplate, setSelectedTemplate] = useState<string>('custom');
  const [customMessage, setCustomMessage] = useState<string>('');
  const [templates, setTemplates] = useState<Array<{ id: number; name: string; content: string }>>([]);
  const [showFilters, setShowFilters] = useState(false);
  const [openActionMenu, setOpenActionMenu] = useState<number | null>(null);
  const [deleteConfirm, setDeleteConfirm] = useState<{ isOpen: boolean; clientId: number | null; clientName: string }>({
    isOpen: false,
    clientId: null,
    clientName: '',
  });
  const messageTextareaRef = useRef<HTMLTextAreaElement | null>(null);

  // WhatsApp integration states
  const [connectedInstances, setConnectedInstances] = useState<Connection[]>([]);
  const [selectedInstance, setSelectedInstance] = useState<number | null>(null);
  const [sendingMessage, setSendingMessage] = useState(false);

  // Bulk selection states
  const [selectedClients, setSelectedClients] = useState<Set<number>>(new Set());
  const [bulkActionLoading, setBulkActionLoading] = useState(false);
  const [fabMenuOpen, setFabMenuOpen] = useState(false);
  const fabRef = useRef<HTMLDivElement>(null);
  const [bulkDeleteConfirm, setBulkDeleteConfirm] = useState<{ isOpen: boolean; count: number }>({
    isOpen: false,
    count: 0,
  });

  useEffect(() => {
    fetchConnectedInstances();
    fetchTemplates();
  }, []);

  // Debounce search term to avoid too many requests
  useEffect(() => {
    const timer = setTimeout(() => {
      setDebouncedSearchTerm(searchTerm);
      // Reset to page 1 when search changes
      setCurrentPage(1);
    }, 500); // 500ms debounce

    return () => clearTimeout(timer);
  }, [searchTerm]);

  const fetchClients = async () => {
    try {
      // Usar loadingClients apenas para a lista, não para a página toda
      setLoadingClients(true);
      const params = new URLSearchParams();
      
      // Pagination
      params.append('page', String(currentPage));
      params.append('per_page', String(perPage));
      
      // Sorting
      params.append('sort_by', sortBy);
      params.append('sort_dir', sortDir);
      
      // Filters
      if (debouncedSearchTerm) params.append('q', debouncedSearchTerm);
      if (statusFilter) params.append('status', statusFilter);
      if (serverFilter) params.append('server_id', serverFilter);
      if (expiresFromFilter) params.append('expires_from', expiresFromFilter);
      if (expiresToFilter) params.append('expires_to', expiresToFilter);

      // Buscar apenas clientes, servidores só se necessário
      const clientsResponse = await api.get(`/clients?${params.toString()}`);
      const clientsData = clientsResponse.data;
      
      // Atualizar apenas os clientes, sem recarregar a página
      setClients(clientsData.data || []);
      
      // Buscar servidores apenas se ainda não foram carregados
      if (servers.length === 0) {
        const serversResponse = await api.get('/servers');
        setServers(serversResponse.data.servers || []);
      }
      
      // Set pagination info
      setPagination({
        current_page: clientsData.current_page || 1,
        last_page: clientsData.last_page || 1,
        per_page: clientsData.per_page || perPage,
        total: clientsData.total || 0,
        from: clientsData.from || 0,
        to: clientsData.to || 0,
      });

    } catch (error) {
      console.error('Failed to fetch clients:', error);
      toast.error('Erro ao carregar clientes');
    } finally {
      setLoadingClients(false);
      // Só usar setLoading(false) na primeira carga
      if (loading) {
        setLoading(false);
      }
    }
  };

  // Fetch clients when filters change
  useEffect(() => {
    fetchClients();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentPage, perPage, sortBy, sortDir, debouncedSearchTerm, statusFilter, serverFilter, expiresFromFilter, expiresToFilter]);

  const fetchTemplates = async () => {
    try {
      const response = await api.get('/message-templates');
      setTemplates(response.data.templates || []);
    } catch (error) {
      console.error('Failed to fetch templates:', error);
    }
  };

  // Update message when template is selected
  useEffect(() => {
    if (whatsappModal && selectedTemplate !== 'custom') {
      const templateId = parseInt(selectedTemplate);
      const template = templates.find(t => t.id === templateId);
      if (template) {
        setCustomMessage(replaceVariables(template.content, whatsappModal));
      }
    } else if (selectedTemplate === 'custom') {
      // Clear message when switching to custom
      setCustomMessage('');
    }
  }, [selectedTemplate, whatsappModal, templates]);

  // Fechar menu FAB ao clicar fora
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (fabRef.current && !fabRef.current.contains(event.target as Node)) {
        setFabMenuOpen(false);
      }
    };

    if (fabMenuOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [fabMenuOpen]);


  const getSortIcon = (field: string) => {
    if (sortBy !== field) return null;
    return sortDir === 'asc' ? <ChevronUp className="w-4 h-4" /> : <ChevronDown className="w-4 h-4" />;
  };

  const fetchConnectedInstances = async () => {
    try {
      const { data } = await api.get('/whatsapp/my-connections');
      const connected = (data.connections || []).filter((c: Connection) => c.status === 'connected');
      setConnectedInstances(connected);

      // Select first instance by default
      if (connected.length > 0 && !selectedInstance) {
        setSelectedInstance(connected[0].id);
      }
    } catch (error) {
      console.error('Failed to fetch WhatsApp instances:', error);
    }
  };

  const handleSort = (field: string) => {
    if (sortBy === field) {
      setSortDir(sortDir === 'asc' ? 'desc' : 'asc');
    } else {
      setSortBy(field);
      setSortDir('asc');
    }
    setCurrentPage(1);
  };

  const handleToggleInactive = async (clientId: number, currentStatus: string) => {
    // Toggle between inactive and active
    // If currently inactive, set to active (will be recalculated if expired)
    // If currently active or expired, set to inactive
    const newStatus = currentStatus === 'inactive' ? 'active' : 'inactive';
    try {
      await api.put(`/clients/${clientId}`, { status: newStatus });
      fetchClients();
      toast.success(newStatus === 'inactive' ? 'Cliente bloqueado com sucesso' : 'Cliente desbloqueado com sucesso');
    } catch (error: any) {
      console.error('Failed to update client status:', error);
      toast.error(error.response?.data?.message || 'Erro ao atualizar status do cliente');
    }
  };

  const handleDeleteClick = (clientId: number, clientName: string) => {
    setDeleteConfirm({
      isOpen: true,
      clientId,
      clientName,
    });
  };

  const handleDeleteConfirm = async () => {
    if (!deleteConfirm.clientId) return;

    try {
      await api.delete(`/clients/${deleteConfirm.clientId}`);
      fetchClients();
      toast.success('Cliente excluído com sucesso');
      setDeleteConfirm({ isOpen: false, clientId: null, clientName: '' });
      setSelectedClients(new Set());
    } catch (error: any) {
      console.error('Failed to delete client:', error);
      toast.error(error.response?.data?.message || 'Erro ao excluir cliente');
    }
  };

  // Bulk selection handlers
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedClients(new Set(clients.map(c => c.id)));
    } else {
      setSelectedClients(new Set());
    }
  };

  const handleSelectClient = (clientId: number, checked: boolean) => {
    const newSelected = new Set(selectedClients);
    if (checked) {
      newSelected.add(clientId);
    } else {
      newSelected.delete(clientId);
    }
    setSelectedClients(newSelected);
  };

  const isAllSelected = clients.length > 0 && selectedClients.size === clients.length;
  const isIndeterminate = selectedClients.size > 0 && selectedClients.size < clients.length;

  // Bulk actions
  const handleBulkDelete = () => {
    setBulkDeleteConfirm({ isOpen: true, count: selectedClients.size });
  };

  const handleBulkDeleteConfirm = async () => {
    if (selectedClients.size === 0) return;

    setBulkActionLoading(true);
    try {
      const clientIds = Array.from(selectedClients);
      const deletePromises = clientIds.map(id => api.delete(`/clients/${id}`));
      await Promise.all(deletePromises);
      
      fetchClients();
      toast.success(`${selectedClients.size} cliente(s) excluído(s) com sucesso`);
      setSelectedClients(new Set());
      setBulkDeleteConfirm({ isOpen: false, count: 0 });
    } catch (error: any) {
      console.error('Failed to delete clients:', error);
      toast.error(error.response?.data?.message || 'Erro ao excluir clientes');
    } finally {
      setBulkActionLoading(false);
    }
  };

  const handleBulkToggleStatus = async (newStatus: 'active' | 'inactive') => {
    if (selectedClients.size === 0) return;

    setBulkActionLoading(true);
    try {
      const clientIds = Array.from(selectedClients);
      const updatePromises = clientIds.map(id => api.put(`/clients/${id}`, { status: newStatus }));
      await Promise.all(updatePromises);
      
      fetchClients();
      toast.success(`${selectedClients.size} cliente(s) ${newStatus === 'inactive' ? 'bloqueado(s)' : 'desbloqueado(s)'} com sucesso`);
      setSelectedClients(new Set());
    } catch (error: any) {
      console.error('Failed to update clients status:', error);
      toast.error(error.response?.data?.message || 'Erro ao atualizar status dos clientes');
    } finally {
      setBulkActionLoading(false);
    }
  };

  const handleExportClients = async () => {
    try {
      const response = await api.get('/clients/export', {
        responseType: 'blob'
      });
      
      // Verificar se a resposta é realmente um blob
      if (!(response.data instanceof Blob)) {
        // Se não for blob, tentar criar um blob do texto
        const blob = new Blob([response.data], { type: 'text/csv;charset=utf-8;' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        const filename = `clientes_${new Date().toISOString().split('T')[0]}.csv`;
        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click();
        setTimeout(() => {
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        }, 100);
      } else {
        const url = window.URL.createObjectURL(response.data);
        const link = document.createElement('a');
        link.href = url;
        const filename = `clientes_${new Date().toISOString().split('T')[0]}.csv`;
        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click();
        setTimeout(() => {
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);
        }, 100);
      }
      toast.success('Clientes exportados com sucesso!');
    } catch (error: any) {
      console.error('Error exporting clients:', error);
      toast.error(error.response?.data?.message || 'Erro ao exportar clientes');
    }
  };

  const replaceVariables = (message: string, client: Client): string => {
    const valor = String(parseFloat(String(client.valor_mensalidade) || '0').toFixed(2));
    const vencimento = formatExpirationDate(client.expires_at);
    
    // Padronizar: APENAS substituir variáveis que estão entre {{}} ou {}
    // Usar regex para garantir que apenas substitua quando estiver entre chaves
    const replacements: Record<string, string> = {
      'nome': client.name,
      'cliente_nome': client.name,
      'usuario': client.username || '-',
      'senha': client.password || '-',
      'servidor': client.server?.name || '-',
      'servidor_nome': client.server?.name || '-',
      'whatsapp': client.whatsapp || '-',
      'cliente_whatsapp': client.whatsapp || '-',
      'valor': valor,
      'cliente_valor': `R$ ${valor}`,
      'vencimento': vencimento,
      'cliente_vencimento': vencimento,
    };
    
    let result = message;
    
    // Substituir {{variavel}} (chaves duplas) - padrão
    for (const [key, value] of Object.entries(replacements)) {
      // Usar regex para garantir que está entre {{}}
      result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, 'g'), value);
    }
    
    // Substituir {variavel} (chave simples) - para compatibilidade
    for (const [key, value] of Object.entries(replacements)) {
      // Usar regex para garantir que está entre {}
      result = result.replace(new RegExp(`\\{${key}\\}`, 'g'), value);
    }
    
    return result;
  };

  const handleSendWhatsApp = async () => {
    if (!whatsappModal) return;

    if (!selectedInstance) {
      toast.warning('Por favor, selecione uma instância do WhatsApp');
      return;
    }

    let message = customMessage;
    
    // If a template is selected (not 'custom'), get its content
    if (selectedTemplate !== 'custom') {
      const templateId = parseInt(selectedTemplate);
      const template = templates.find(t => t.id === templateId);
      if (template) {
        message = replaceVariables(template.content, whatsappModal);
      }
    }
    message = replaceVariables(message, whatsappModal);

    // Get phone number and clean it
    let phone = whatsappModal.whatsapp;
    if (!phone || phone.trim() === '') {
      toast.warning('Cliente não possui WhatsApp cadastrado');
      return;
    }
    
    // Remove all non-numeric characters
    phone = phone.replace(/\D/g, '');
    
    // Validate phone number length (8-15 digits)
    if (phone.length < 8 || phone.length > 15) {
      toast.error(`Número de WhatsApp inválido: ${whatsappModal.whatsapp}. O número deve ter entre 8 e 15 dígitos.`);
      console.error('Invalid phone number:', {
        original: whatsappModal.whatsapp,
        cleaned: phone,
        length: phone.length,
        client_id: whatsappModal.id,
      });
      return;
    }

    try {
      setSendingMessage(true);

      await api.post('/whatsapp/send-message', {
        to_number: phone,
        message: message,
        connection_id: selectedInstance,
        client_id: whatsappModal.id
      });

      toast.success('Mensagem enviada com sucesso!');
      setWhatsappModal(null);
      // Atualizar apenas a lista sem recarregar a página
      fetchClients();
    } catch (error: any) {
      console.error('Failed to send WhatsApp message:', error);
      const errorMessage = error.response?.data?.message || 'Erro ao enviar mensagem. Tente novamente.';
      toast.error(errorMessage);
    } finally {
      setSendingMessage(false);
    }
  };

  const handleBulkSendWhatsApp = async () => {
    if (selectedClients.size === 0) return;

    if (!selectedInstance) {
      toast.warning('Por favor, selecione uma instância do WhatsApp');
      return;
    }

    const selectedClientsList = clients.filter(c => selectedClients.has(c.id));
    const clientsWithWhatsapp = selectedClientsList.filter(c => c.whatsapp);

    if (clientsWithWhatsapp.length === 0) {
      toast.warning('Nenhum dos clientes selecionados possui WhatsApp cadastrado');
      return;
    }

    let message = customMessage;
    
    // If a template is selected (not 'custom'), use it as base
    if (selectedTemplate !== 'custom') {
      const templateId = parseInt(selectedTemplate);
      const template = templates.find(t => t.id === templateId);
      if (template) {
        message = template.content;
      }
    }

    try {
      setSendingMessage(true);
      let successCount = 0;
      let errorCount = 0;

      // Send to each client with their variables replaced
      for (const client of clientsWithWhatsapp) {
        try {
          const clientMessage = replaceVariables(message, client);
          
          // Get and validate phone number
          let phone = client.whatsapp;
          if (!phone || phone.trim() === '') {
            console.warn(`Client ${client.name} (ID: ${client.id}) has empty WhatsApp number`);
            errorCount++;
            continue;
          }
          
          // Remove all non-numeric characters
          phone = phone.replace(/\D/g, '');
          
          // Validate phone number length (8-15 digits)
          if (phone.length < 8 || phone.length > 15) {
            console.error(`Invalid phone number for client ${client.name} (ID: ${client.id}):`, {
              original: client.whatsapp,
              cleaned: phone,
              length: phone.length,
            });
            errorCount++;
            continue;
          }

          await api.post('/whatsapp/send-message', {
            to_number: phone,
            message: clientMessage,
            connection_id: selectedInstance,
            client_id: client.id
          });

          successCount++;
        } catch (error: any) {
          console.error(`Failed to send to ${client.name}:`, error);
          const errorMsg = error.response?.data?.message || error.message || 'Erro desconhecido';
          console.error(`Error details for client ${client.name} (ID: ${client.id}):`, {
            error: errorMsg,
            whatsapp: client.whatsapp,
          });
          errorCount++;
        }
      }

      if (successCount > 0) {
        toast.success(`${successCount} mensagem(ns) enviada(s) com sucesso!${errorCount > 0 ? ` (${errorCount} erro(s))` : ''}`);
      } else {
        toast.error('Nenhuma mensagem foi enviada. Verifique os erros.');
      }

      setBulkWhatsappModal(false);
      setSelectedClients(new Set());
      setCustomMessage('');
      setSelectedTemplate('custom');
      // Atualizar apenas a lista sem recarregar a página
      fetchClients();
    } catch (error: any) {
      console.error('Failed to send bulk WhatsApp messages:', error);
      toast.error('Erro ao enviar mensagens. Tente novamente.');
    } finally {
      setSendingMessage(false);
    }
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active':
        return 'bg-green-100 text-green-800';
      case 'expired':
        return 'bg-red-100 text-red-800';
      case 'inactive':
        return 'bg-yellow-100 text-yellow-800';
      default:
        return 'bg-gray-100 text-gray-800';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'active': return 'Ativo';
      case 'expired': return 'Vencido';
      case 'inactive': return 'Inativo';
      default: return status;
    }
  };

  if (loading) {
    return (
      <Layout title="Clientes">
        <div className="flex items-center justify-center h-64">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2" style={{ borderColor: '#7C3AED' }}></div>
        </div>
      </Layout>
    );
  }

  return (
    <Layout title="Clientes">

      {/* Pagination Controls - Top */}
      {pagination && (
        <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3 sm:gap-4 bg-white p-3 sm:p-4 rounded-lg shadow mb-4 sm:mb-6">
          <div className="flex items-center gap-2 flex-wrap">
            <label className="text-xs sm:text-sm text-gray-700 whitespace-nowrap">Itens por página:</label>
            <select
              value={perPage}
              onChange={(e) => {
                setPerPage(Number(e.target.value));
                setCurrentPage(1);
              }}
              className="border border-gray-300 rounded px-2 py-1 text-xs sm:text-sm"
            >
              <option value={10}>10</option>
              <option value={25}>25</option>
              <option value={50}>50</option>
              <option value={100}>100</option>
              <option value={200}>200</option>
            </select>
          </div>
          <div className="flex flex-col sm:flex-row items-start sm:items-center gap-2">
            <span className="text-xs sm:text-sm text-gray-700 whitespace-nowrap">
              Página {pagination.current_page} de {pagination.last_page} ({pagination.total} total)
            </span>
            <div className="flex gap-1">
              <button
                onClick={() => setCurrentPage(1)}
                disabled={pagination.current_page === 1}
                className="px-2 py-1 border border-gray-300 rounded disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
              >
                <ChevronLeft className="w-4 h-4" />
              </button>
              <input
                type="number"
                min={1}
                max={pagination.last_page}
                value={currentPage}
                onChange={(e) => {
                  const page = Number(e.target.value);
                  if (page >= 1 && page <= pagination.last_page) {
                    setCurrentPage(page);
                  }
                }}
                className="w-16 px-2 py-1 border border-gray-300 rounded text-center text-sm"
              />
              <button
                onClick={() => setCurrentPage(pagination.last_page)}
                disabled={pagination.current_page === pagination.last_page}
                className="px-2 py-1 border border-gray-300 rounded disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
              >
                <ChevronRight className="w-4 h-4" />
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Search and Filters */}
      <div className="card mb-6 p-4 md:p-6">
        <div className="flex flex-col gap-4">
          {/* Busca */}
          <div className="w-full">
            <input
              type="text"
              placeholder="Buscar por nome, usuário, WhatsApp, servidor ou data (ex: 13/12/2025, 12/01, 01/2026, 2026)..."
              value={searchTerm}
              onChange={(e) => {
                e.preventDefault();
                setSearchTerm(e.target.value);
              }}
              onKeyDown={(e) => {
                if (e.key === 'Enter') {
                  e.preventDefault();
                }
              }}
              className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
            />
          </div>

          {/* Botões - Responsivos */}
          <div className="grid grid-cols-2 sm:flex sm:flex-wrap gap-2">
            <button
              onClick={() => setShowFilters(!showFilters)}
              className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors flex items-center justify-center gap-2 text-sm whitespace-nowrap"
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
              </svg>
              <span className="hidden sm:inline">Filtros</span>
              <span className="sm:hidden">Filtro</span>
            </button>

            <button
              onClick={handleExportClients}
              className="px-3 py-2 border border-green-600 text-green-600 rounded-lg hover:bg-green-50 transition-colors flex items-center justify-center gap-2 text-sm whitespace-nowrap"
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
              </svg>
              <span className="hidden sm:inline">Exportar</span>
              <span className="sm:hidden">Export</span>
            </button>

            <Link
              to="/clients/import"
              className="px-3 py-2 border border-blue-600 text-blue-600 rounded-lg hover:bg-blue-50 transition-colors flex items-center justify-center gap-2 text-sm whitespace-nowrap"
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
              </svg>
              <span className="hidden sm:inline">Importar</span>
              <span className="sm:hidden">Import</span>
            </Link>

            <Link
              to="/clients/new"
              className="col-span-2 sm:col-span-1 px-4 py-2 rounded-lg text-white font-medium transition-colors flex items-center justify-center gap-2 text-sm whitespace-nowrap"
              style={{ backgroundColor: '#7C3AED' }}
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
              </svg>
              Novo Cliente
            </Link>
          </div>

          {showFilters && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 pt-4 border-t border-gray-200">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Status</label>
                <select
                  value={statusFilter}
                  onChange={(e) => {
                    setStatusFilter(e.target.value);
                    setCurrentPage(1);
                  }}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                >
                  <option value="">Todos</option>
                  <option value="active">Ativo</option>
                  <option value="expired">Vencido</option>
                  <option value="suspended">Bloqueado</option>
                  <option value="inactive">Inativo</option>
                </select>
              </div>
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">Servidor</label>
                <select
                  value={serverFilter}
                  onChange={(e) => {
                    setServerFilter(e.target.value);
                    setCurrentPage(1);
                  }}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                >
                  <option value="">Todos</option>
                  {servers.map(server => (
                    <option key={server.id} value={String(server.id)}>{server.name}</option>
                  ))}
                </select>
              </div>
              <div>
                <DatePicker
                  label="Vencimento De"
                  value={expiresFromFilter}
                  onChange={(value) => {
                    setExpiresFromFilter(value);
                    setCurrentPage(1);
                  }}
                />
              </div>
              <div>
                <DatePicker
                  label="Vencimento Até"
                  value={expiresToFilter}
                  onChange={(value) => {
                    setExpiresToFilter(value);
                    setCurrentPage(1);
                  }}
                  min={expiresFromFilter || undefined}
                />
              </div>
              {(expiresFromFilter || expiresToFilter) && (
                <div className="md:col-span-2">
                  <button
                    onClick={() => {
                      setExpiresFromFilter('');
                      setExpiresToFilter('');
                      setCurrentPage(1);
                    }}
                    className="text-sm text-red-600 hover:text-red-800 underline"
                  >
                    Limpar filtros de data
                  </button>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Clients Table - Desktop */}
      <div className="card overflow-hidden hidden md:block">
        <div className="overflow-x-auto -mx-3 sm:mx-0">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-4 text-left text-xs font-medium text-text-secondary uppercase tracking-wider w-12">
                  <input
                    type="checkbox"
                    checked={isAllSelected}
                    ref={(input) => {
                      if (input) input.indeterminate = isIndeterminate;
                    }}
                    onChange={(e) => handleSelectAll(e.target.checked)}
                    className="w-4 h-4 text-purple-600 border-gray-300 rounded focus:ring-purple-500"
                  />
                </th>
                <th 
                  className="px-6 py-4 text-left text-xs font-medium text-text-secondary uppercase tracking-wider cursor-pointer hover:bg-gray-100 select-none"
                  onClick={() => handleSort('name')}
                >
                  <div className="flex items-center gap-1">
                    Cliente
                    {getSortIcon('name')}
                  </div>
                </th>
                <th 
                  className="px-6 py-4 text-left text-xs font-medium text-text-secondary uppercase tracking-wider cursor-pointer hover:bg-gray-100 select-none"
                  onClick={() => handleSort('whatsapp')}
                >
                  <div className="flex items-center gap-1">
                    WhatsApp
                    {getSortIcon('whatsapp')}
                  </div>
                </th>
                <th 
                  className="px-6 py-4 text-left text-xs font-medium text-text-secondary uppercase tracking-wider cursor-pointer hover:bg-gray-100 select-none"
                  onClick={() => handleSort('server_id')}
                >
                  <div className="flex items-center gap-1">
                    Servidor
                    {getSortIcon('server_id')}
                  </div>
                </th>
                <th 
                  className="px-6 py-4 text-left text-xs font-medium text-text-secondary uppercase tracking-wider cursor-pointer hover:bg-gray-100 select-none"
                  onClick={() => handleSort('status')}
                >
                  <div className="flex items-center gap-1">
                    Status
                    {getSortIcon('status')}
                  </div>
                </th>
                <th 
                  className="px-6 py-4 text-left text-xs font-medium text-text-secondary uppercase tracking-wider cursor-pointer hover:bg-gray-100 select-none"
                  onClick={() => handleSort('expires_at')}
                >
                  <div className="flex items-center gap-1">
                    Vencimento
                    {getSortIcon('expires_at')}
                  </div>
                </th>
                <th 
                  className="px-6 py-4 text-left text-xs font-medium text-text-secondary uppercase tracking-wider cursor-pointer hover:bg-gray-100 select-none"
                  onClick={() => handleSort('valor_mensalidade')}
                >
                  <div className="flex items-center gap-1">
                    Valor
                    {getSortIcon('valor_mensalidade')}
                  </div>
                </th>
                <th className="px-6 py-4 text-right text-xs font-medium text-text-secondary uppercase tracking-wider">
                  Ações
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-100">
              {loadingClients ? (
                <tr>
                  <td colSpan={8} className="px-6 py-8 text-center">
                    <div className="flex items-center justify-center">
                      <div className="animate-spin rounded-full h-6 w-6 border-b-2" style={{ borderColor: '#7C3AED' }}></div>
                      <span className="ml-2 text-sm text-gray-600">Carregando...</span>
                    </div>
                  </td>
                </tr>
              ) : clients.length === 0 ? (
                <tr>
                  <td colSpan={8} className="px-6 py-8 text-center text-sm text-gray-500">
                    Nenhum cliente encontrado
                  </td>
                </tr>
              ) : (
                clients.map((client) => (
                <tr key={client.id} className={`hover:bg-gray-50 transition-colors ${selectedClients.has(client.id) ? 'bg-purple-50' : ''}`}>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <input
                      type="checkbox"
                      checked={selectedClients.has(client.id)}
                      onChange={(e) => handleSelectClient(client.id, e.target.checked)}
                      className="w-4 h-4 text-purple-600 border-gray-300 rounded focus:ring-purple-500"
                    />
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div>
                      <div className="text-sm font-medium text-text-title">{client.name}</div>
                      {client.username && (
                        <div className="text-sm text-text-secondary">{client.username}</div>
                      )}
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="flex items-center gap-2">
                      {client.whatsapp ? (
                        <>
                          <svg className="w-4 h-4 text-green-600" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z" />
                          </svg>
                          <span className="text-sm text-text-normal">{client.whatsapp}</span>
                        </>
                      ) : (
                        <span className="text-sm text-gray-400">Não informado</span>
                      )}
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className="text-sm text-text-normal">{client.server?.name || '-'}</span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <span className={`px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full ${getStatusColor(client.status)}`}>
                      {getStatusText(client.status)}
                    </span>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm text-text-normal">
                    {formatExpirationDate(client.expires_at)}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-text-normal">
                    R$ {parseFloat(String(client.valor_mensalidade) || '0').toFixed(2)}
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                    <div className="flex items-center justify-end gap-2">
                      {/* Editar */}
                      <button
                        onClick={() => setEditClient(client)}
                        className="text-blue-600 hover:text-blue-800 p-2 rounded hover:bg-blue-50 transition-colors"
                        title="Editar"
                      >
                        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                        </svg>
                      </button>

                      {/* Renovar */}
                      <button
                        onClick={() => setRenewalClient({ id: client.id, name: client.name })}
                        className="text-green-600 hover:text-green-800 p-2 rounded hover:bg-green-50 transition-colors"
                        title="Renovar"
                      >
                        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                        </svg>
                      </button>

                      {/* Bloquear/Desbloquear (Inativo) */}
                      <button
                        onClick={() => handleToggleInactive(client.id, client.status)}
                        className={`p-2 rounded transition-colors ${client.status === 'inactive'
                          ? 'text-green-600 hover:text-green-800 hover:bg-green-50'
                          : 'text-yellow-600 hover:text-yellow-800 hover:bg-yellow-50'
                          }`}
                        title={client.status === 'inactive' ? 'Desbloquear' : 'Bloquear'}
                      >
                        {client.status === 'inactive' ? (
                          <Unlock className="w-5 h-5" />
                        ) : (
                          <Lock className="w-5 h-5" />
                        )}
                      </button>

                      {/* WhatsApp */}
                      {connectedInstances.length > 0 && (
                        <button
                          onClick={() => setWhatsappModal(client)}
                          className="text-emerald-600 hover:text-emerald-800 p-2 rounded hover:bg-emerald-50 transition-colors"
                          title="Enviar WhatsApp"
                          disabled={!client.whatsapp}
                        >
                          <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
                          </svg>
                        </button>
                      )}

                      {/* Excluir */}
                      <button
                        onClick={() => handleDeleteClick(client.id, client.name)}
                        className="text-red-600 hover:text-red-800 p-2 rounded hover:bg-red-50 transition-colors"
                        title="Excluir"
                      >
                        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                        </svg>
                      </button>
                    </div>
                  </td>
                </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Clients Cards - Mobile */}
      <div className="md:hidden space-y-4">
        {/* Sort Selector for Mobile */}
        <div className="card p-4">
          <div className="flex items-center gap-2">
            <label className="text-sm font-medium text-gray-700">Ordenar por:</label>
            <select
              value={`${sortBy}_${sortDir}`}
              onChange={(e) => {
                const [field, dir] = e.target.value.split('_');
                setSortBy(field);
                setSortDir(dir as 'asc' | 'desc');
                setCurrentPage(1);
              }}
              className="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent text-sm"
            >
              <option value="expires_at_asc">Vencimento (Mais próximo)</option>
              <option value="expires_at_desc">Vencimento (Mais distante)</option>
              <option value="name_asc">Nome (A-Z)</option>
              <option value="name_desc">Nome (Z-A)</option>
              <option value="valor_mensalidade_desc">Valor (Maior)</option>
              <option value="valor_mensalidade_asc">Valor (Menor)</option>
              <option value="status_asc">Status (A-Z)</option>
              <option value="status_desc">Status (Z-A)</option>
            </select>
          </div>
        </div>
        {loadingClients ? (
          <div className="text-center py-12">
            <div className="flex items-center justify-center">
              <div className="animate-spin rounded-full h-6 w-6 border-b-2" style={{ borderColor: '#7C3AED' }}></div>
              <span className="ml-2 text-sm text-gray-600">Carregando...</span>
            </div>
          </div>
        ) : clients.length === 0 ? (
          <div className="text-center py-12">
            <svg className="mx-auto h-12 w-12 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
            </svg>
            <p className="mt-4 text-sm text-text-secondary">Nenhum cliente encontrado</p>
          </div>
        ) : (
          clients.map((client) => (
          <div key={client.id} className={`card p-4 ${selectedClients.has(client.id) ? 'ring-2 ring-purple-500' : ''}`}>
            {/* Header com checkbox, nome e status */}
            <div className="flex items-start justify-between mb-3">
              <div className="flex items-start gap-3 flex-1">
                <input
                  type="checkbox"
                  checked={selectedClients.has(client.id)}
                  onChange={(e) => handleSelectClient(client.id, e.target.checked)}
                  className="w-4 h-4 text-purple-600 border-gray-300 rounded focus:ring-purple-500 mt-1"
                />
                <div className="flex-1">
                  <h3 className="font-semibold text-text-title text-base">{client.name}</h3>
                  {client.username && (
                    <p className="text-sm text-text-secondary mt-1">{client.username}</p>
                  )}
                </div>
              </div>
              <span className={`px-2 py-1 text-xs font-semibold rounded-full whitespace-nowrap ${getStatusColor(client.status)}`}>
                {getStatusText(client.status)}
              </span>
            </div>

            {/* Informações */}
            <div className="space-y-2 mb-3">
              {/* WhatsApp */}
              <div className="flex items-center gap-2">
                <svg className="w-4 h-4 text-green-600 flex-shrink-0" fill="currentColor" viewBox="0 0 24 24">
                  <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
                </svg>
                <span className="text-sm text-text-normal truncate">
                  {client.whatsapp || 'Não informado'}
                </span>
              </div>

              {/* Servidor */}
              <div className="flex items-center gap-2">
                <svg className="w-4 h-4 text-gray-500 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01" />
                </svg>
                <span className="text-sm text-text-normal truncate">{client.server?.name || '-'}</span>
              </div>

              {/* Vencimento e Valor */}
              <div className="flex items-center justify-between pt-2 border-t border-gray-100">
                <div className="flex items-center gap-2">
                  <svg className="w-4 h-4 text-gray-500 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                  </svg>
                  <span className="text-sm text-text-secondary">
                    {formatExpirationDate(client.expires_at)}
                  </span>
                </div>
                <span className="text-sm font-semibold text-text-title">
                  R$ {parseFloat(String(client.valor_mensalidade) || '0').toFixed(2)}
                </span>
              </div>
            </div>

            {/* Ações */}
            <div className="relative flex items-center gap-2 pt-3 border-t border-gray-100">
              {/* Botões principais */}
              <button
                onClick={() => setEditClient(client)}
                className="flex-1 px-3 py-2 border border-blue-600 text-blue-600 rounded-lg hover:bg-blue-50 transition-colors flex items-center justify-center gap-2 text-sm"
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                </svg>
                Editar
              </button>

              <button
                onClick={() => {
                  setRenewalClient({ id: client.id, name: client.name });
                }}
                className="flex-1 px-3 py-2 border border-green-600 text-green-600 rounded-lg hover:bg-green-50 transition-colors flex items-center justify-center gap-2 text-sm"
              >
                <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                </svg>
                Renovar
              </button>

              {/* Menu de Mais Opções */}
              <div className="relative">
                <button
                  onClick={() => setOpenActionMenu(openActionMenu === client.id ? null : client.id)}
                  className="px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  <svg className="w-5 h-5 text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z" />
                  </svg>
                </button>

                {/* Dropdown Menu */}
                {openActionMenu === client.id && (
                  <>
                    <div
                      className="fixed inset-0 z-10"
                      onClick={() => setOpenActionMenu(null)}
                    />
                    <div className="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg border border-gray-200 py-1 z-20">
                      <button
                        onClick={() => {
                          handleToggleInactive(client.id, client.status);
                          setOpenActionMenu(null);
                        }}
                        className="w-full px-4 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-2"
                      >
                        {client.status === 'inactive' ? (
                          <Unlock className="w-4 h-4" />
                        ) : (
                          <Lock className="w-4 h-4" />
                        )}
                        {client.status === 'inactive' ? 'Desbloquear' : 'Bloquear'}
                      </button>

                      {connectedInstances.length > 0 && (
                        <button
                          onClick={() => {
                            setWhatsappModal(client);
                            setOpenActionMenu(null);
                          }}
                          disabled={!client.whatsapp}
                          className="w-full px-4 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
                        >
                          <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                            <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
                          </svg>
                          WhatsApp
                        </button>
                      )}

                      <button
                        onClick={() => {
                          handleDeleteClick(client.id, client.name);
                          setOpenActionMenu(null);
                        }}
                        className="w-full px-4 py-2 text-left text-sm text-red-600 hover:bg-red-50 flex items-center gap-2"
                      >
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                        </svg>
                        Excluir
                      </button>
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>
          ))
        )}

        {!loadingClients && clients.length === 0 && (
          <div className="card p-12 text-center">
            <svg className="mx-auto h-12 w-12 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
            </svg>
            <p className="mt-4 text-sm text-text-secondary">Nenhum cliente encontrado</p>
          </div>
        )}
      </div>

      {/* WhatsApp Modal */}
      {whatsappModal && (
        <div
          className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-3 sm:p-4"
          onClick={(e) => {
            if (e.target === e.currentTarget) {
              setWhatsappModal(null);
            }
          }}
        >
          <div className="bg-white rounded-xl sm:rounded-2xl w-full max-w-2xl max-h-[95vh] sm:max-h-[90vh] flex flex-col shadow-2xl m-2 sm:m-0">
            <div className="flex justify-between items-center p-3 sm:p-4 md:p-6 border-b border-gray-200 flex-shrink-0">
              <h3 className="text-base sm:text-lg md:text-xl font-bold text-gray-800 truncate pr-2">Enviar WhatsApp</h3>
              <button
                onClick={() => setWhatsappModal(null)}
                className="text-gray-400 hover:text-gray-600 text-2xl flex-shrink-0"
                aria-label="Fechar"
              >
                ×
              </button>
            </div>

            <div className="p-3 sm:p-4 md:p-6 space-y-3 sm:space-y-4 overflow-y-auto flex-1">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Cliente
                </label>
                <input
                  type="text"
                  value={whatsappModal.name}
                  disabled
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-50"
                />
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  WhatsApp
                </label>
                <input
                  type="text"
                  value={whatsappModal.whatsapp || 'Não cadastrado'}
                  disabled
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-50"
                />
              </div>

              {/* Instance Selector */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  📱 Instância WhatsApp
                </label>
                {connectedInstances.length === 0 ? (
                  <div className="w-full px-4 py-2 border border-yellow-300 bg-yellow-50 rounded-lg text-yellow-800 text-sm">
                    ⚠️ Nenhuma instância conectada. <Link to="/whatsapp" className="underline font-semibold">Conectar agora</Link>
                  </div>
                ) : (
                  <select
                    value={selectedInstance || ''}
                    onChange={(e) => setSelectedInstance(Number(e.target.value))}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                  >
                    {connectedInstances.map(instance => (
                      <option key={instance.id} value={instance.id}>
                        {instance.instance_name} {instance.phone_number ? `(${instance.phone_number})` : ''}
                      </option>
                    ))}
                  </select>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Modelo de Mensagem
                </label>
                <select
                  value={selectedTemplate}
                  onChange={(e) => {
                    setSelectedTemplate(e.target.value);
                    if (e.target.value === 'custom') {
                      setCustomMessage('');
                    } else {
                      const templateId = parseInt(e.target.value);
                      const template = templates.find(t => t.id === templateId);
                      if (template) {
                        setCustomMessage(replaceVariables(template.content, whatsappModal));
                      }
                    }
                  }}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                >
                  <option value="custom">Mensagem Personalizada</option>
                  {templates.map(template => (
                    <option key={template.id} value={template.id.toString()}>{template.name}</option>
                  ))}
                </select>
              </div>

              <div>
                {whatsappModal && (
                  <VariableSelector
                    textareaRef={messageTextareaRef}
                    value={customMessage}
                    onChange={setCustomMessage}
                    label="Mensagem"
                    customVariables={[
                      {
                        category: 'Cliente',
                        items: [
                          { key: 'nome', label: 'Nome do Cliente', example: whatsappModal.name },
                          { key: 'usuario', label: 'Usuário', example: whatsappModal.username || 'N/A' },
                          { key: 'senha', label: 'Senha', example: whatsappModal.password || 'N/A' },
                          { key: 'servidor', label: 'Servidor', example: whatsappModal.server?.name || 'N/A' },
                          { key: 'whatsapp', label: 'WhatsApp', example: whatsappModal.whatsapp || 'N/A' },
                          { key: 'valor', label: 'Valor', example: `R$ ${parseFloat(String(whatsappModal.valor_mensalidade || 0)).toFixed(2)}` },
                          { key: 'vencimento', label: 'Vencimento', example: formatExpirationDate(whatsappModal.expires_at) || 'N/A' },
                        ]
                      }
                    ]}
                  />
                )}
                {!whatsappModal || selectedTemplate !== 'custom' ? (
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Mensagem
                  </label>
                ) : null}
                <textarea
                  ref={messageTextareaRef}
                  value={selectedTemplate === 'custom' 
                    ? customMessage 
                    : (() => {
                        // If template is selected, use API template, not hardcoded
                        if (selectedTemplate !== 'custom') {
                          const templateId = parseInt(selectedTemplate);
                          const template = templates.find(t => t.id === templateId);
                          if (template) {
                            return replaceVariables(template.content, whatsappModal);
                          }
                        }
                        return customMessage;
                      })()}
                  onChange={(e) => {
                    if (selectedTemplate === 'custom') {
                      setCustomMessage(e.target.value);
                    }
                  }}
                  disabled={selectedTemplate !== 'custom'}
                  rows={5}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent disabled:bg-gray-50"
                  placeholder="Digite sua mensagem personalizada..."
                />
              </div>
            </div>

            <div className="flex flex-col sm:flex-row gap-2 sm:gap-3 p-4 sm:p-6 border-t border-gray-200 bg-gray-50 rounded-b-xl sm:rounded-b-2xl">
              <button
                type="button"
                onClick={() => setWhatsappModal(null)}
                className="flex-1 px-4 sm:px-6 py-2 sm:py-3 border border-gray-300 rounded-lg text-gray-700 font-medium hover:bg-gray-100 transition-colors text-sm sm:text-base"
              >
                Cancelar
              </button>
              <button
                type="button"
                onClick={handleSendWhatsApp}
                disabled={!whatsappModal.whatsapp || !selectedInstance || sendingMessage}
                className="flex-1 px-4 sm:px-6 py-2 sm:py-3 rounded-lg text-white font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm sm:text-base"
                style={{ backgroundColor: '#10B981' }}
              >
                {sendingMessage ? (
                  <>
                    <svg className="animate-spin h-5 w-5" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    Enviando...
                  </>
                ) : (
                  <>
                    <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
                    </svg>
                    Enviar WhatsApp
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Bulk WhatsApp Modal */}
      {bulkWhatsappModal && (
        <div
          className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-3 sm:p-4"
          onClick={(e) => {
            if (e.target === e.currentTarget) {
              setBulkWhatsappModal(false);
            }
          }}
        >
          <div className="bg-white rounded-xl sm:rounded-2xl w-full max-w-2xl max-h-[95vh] sm:max-h-[90vh] flex flex-col shadow-2xl m-2 sm:m-0">
            <div className="flex justify-between items-center p-3 sm:p-4 md:p-6 border-b border-gray-200 flex-shrink-0">
              <h3 className="text-base sm:text-lg md:text-xl font-bold text-gray-800 truncate pr-2">
                Enviar WhatsApp em Lote ({selectedClients.size} cliente(s))
              </h3>
              <button
                onClick={() => setBulkWhatsappModal(false)}
                className="text-gray-400 hover:text-gray-600 text-2xl flex-shrink-0"
                aria-label="Fechar"
              >
                ×
              </button>
            </div>

            <div className="p-3 sm:p-4 md:p-6 space-y-3 sm:space-y-4 overflow-y-auto flex-1">
              <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
                <p className="text-sm text-blue-800">
                  📢 A mensagem será enviada para {clients.filter(c => selectedClients.has(c.id) && c.whatsapp).length} cliente(s) com WhatsApp cadastrado.
                  <br />
                  As variáveis (como {`{nome}`}, {`{usuario}`}, etc.) serão substituídas automaticamente para cada cliente.
                </p>
              </div>

              {/* Instance Selector */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  📱 Instância WhatsApp
                </label>
                {connectedInstances.length === 0 ? (
                  <div className="w-full px-4 py-2 border border-yellow-300 bg-yellow-50 rounded-lg text-yellow-800 text-sm">
                    ⚠️ Nenhuma instância conectada. <Link to="/whatsapp" className="underline font-semibold">Conectar agora</Link>
                  </div>
                ) : (
                  <select
                    value={selectedInstance || ''}
                    onChange={(e) => setSelectedInstance(Number(e.target.value))}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                  >
                    {connectedInstances.map(instance => (
                      <option key={instance.id} value={instance.id}>
                        {instance.instance_name} {instance.phone_number ? `(${instance.phone_number})` : ''}
                      </option>
                    ))}
                  </select>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Modelo de Mensagem
                </label>
                <select
                  value={selectedTemplate}
                  onChange={(e) => {
                    setSelectedTemplate(e.target.value);
                    if (e.target.value === 'custom') {
                      setCustomMessage('');
                    } else {
                      const templateId = parseInt(e.target.value);
                      const template = templates.find(t => t.id === templateId);
                      if (template) {
                        setCustomMessage(template.content);
                      }
                    }
                  }}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                >
                  <option value="custom">Mensagem Personalizada</option>
                  {templates.map(template => (
                    <option key={template.id} value={template.id.toString()}>{template.name}</option>
                  ))}
                </select>
              </div>

              <div>
                <VariableSelector
                  textareaRef={messageTextareaRef}
                  value={customMessage}
                  onChange={setCustomMessage}
                  label="Mensagem"
                  customVariables={[
                    {
                      category: 'Cliente',
                      items: [
                        { key: 'nome', label: 'Nome do Cliente', example: 'João Silva' },
                        { key: 'usuario', label: 'Usuário', example: 'joao123' },
                        { key: 'senha', label: 'Senha', example: 'senha123' },
                        { key: 'servidor', label: 'Servidor', example: 'Servidor 1' },
                        { key: 'whatsapp', label: 'WhatsApp', example: '5511999999999' },
                        { key: 'valor', label: 'Valor', example: 'R$ 50.00' },
                        { key: 'vencimento', label: 'Vencimento', example: '31/12/2024' },
                      ]
                    }
                  ]}
                />
                <textarea
                  ref={messageTextareaRef}
                  value={customMessage}
                  onChange={(e) => setCustomMessage(e.target.value)}
                  rows={8}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent mt-2"
                  placeholder="Digite sua mensagem personalizada. Use variáveis como {nome}, {usuario}, {senha}, etc."
                />
              </div>
            </div>

            <div className="flex flex-col sm:flex-row gap-2 sm:gap-3 p-4 sm:p-6 border-t border-gray-200 bg-gray-50 rounded-b-xl sm:rounded-b-2xl">
              <button
                type="button"
                onClick={() => {
                  setBulkWhatsappModal(false);
                  setCustomMessage('');
                  setSelectedTemplate('custom');
                }}
                className="flex-1 px-4 sm:px-6 py-2 sm:py-3 border border-gray-300 rounded-lg text-gray-700 font-medium hover:bg-gray-100 transition-colors text-sm sm:text-base"
              >
                Cancelar
              </button>
              <button
                type="button"
                onClick={handleBulkSendWhatsApp}
                disabled={!selectedInstance || sendingMessage || !customMessage.trim()}
                className="flex-1 px-4 sm:px-6 py-2 sm:py-3 rounded-lg text-white font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2 text-sm sm:text-base"
                style={{ backgroundColor: '#10B981' }}
              >
                {sendingMessage ? (
                  <>
                    <svg className="animate-spin h-5 w-5" fill="none" viewBox="0 0 24 24">
                      <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                      <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    Enviando...
                  </>
                ) : (
                  <>
                    <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
                    </svg>
                    Enviar para {clients.filter(c => selectedClients.has(c.id) && c.whatsapp).length} Cliente(s)
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Renewal Modal */}
      {renewalClient && (
        <RenewalModal
          clientId={renewalClient.id}
          clientName={renewalClient.name}
          onClose={() => setRenewalClient(null)}
          onSuccess={() => {
            setRenewalClient(null);
            fetchClients();
          }}
          alwaysRenewal={true}
        />
      )}

      {/* Floating Action Button (FAB) for Bulk Actions */}
      {selectedClients.size > 0 && (
        <div ref={fabRef} className="fixed bottom-6 right-6 z-50">
          {/* Menu de ações */}
          {fabMenuOpen && (
            <div className="absolute bottom-16 right-0 mb-2 w-56 bg-white rounded-lg shadow-xl border border-gray-200 overflow-hidden animate-in slide-in-from-bottom-2">
              <div className="p-2 border-b border-gray-200 bg-purple-50">
                <div className="text-sm font-semibold text-purple-900">
                  {selectedClients.size} cliente(s) selecionado(s)
                </div>
              </div>
              <div className="py-1">
                {connectedInstances.length > 0 && (
                  <button
                    onClick={() => {
                      const selectedClientsList = clients.filter(c => selectedClients.has(c.id));
                      const clientsWithWhatsapp = selectedClientsList.filter(c => c.whatsapp);
                      if (clientsWithWhatsapp.length === 0) {
                        toast.warning('Nenhum dos clientes selecionados possui WhatsApp cadastrado');
                        setFabMenuOpen(false);
                        return;
                      }
                      setBulkWhatsappModal(true);
                      setFabMenuOpen(false);
                    }}
                    disabled={bulkActionLoading}
                    className="w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-emerald-50 hover:text-emerald-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-3"
                  >
                    <svg className="w-5 h-5" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z" />
                    </svg>
                    <span>Enviar WhatsApp</span>
                  </button>
                )}
                <button
                  onClick={() => {
                    handleBulkToggleStatus('inactive');
                    setFabMenuOpen(false);
                  }}
                  disabled={bulkActionLoading}
                  className="w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-yellow-50 hover:text-yellow-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-3"
                >
                  <Lock className="w-5 h-5" />
                  <span>Bloquear</span>
                </button>
                <button
                  onClick={() => {
                    handleBulkToggleStatus('active');
                    setFabMenuOpen(false);
                  }}
                  disabled={bulkActionLoading}
                  className="w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-green-50 hover:text-green-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-3"
                >
                  <Unlock className="w-5 h-5" />
                  <span>Desbloquear</span>
                </button>
                <button
                  onClick={() => {
                    handleBulkDelete();
                    setFabMenuOpen(false);
                  }}
                  disabled={bulkActionLoading}
                  className="w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-red-50 hover:text-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-3"
                >
                  <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                  <span>Excluir</span>
                </button>
                <div className="border-t border-gray-200 mt-1 pt-1">
                  <button
                    onClick={() => {
                      setSelectedClients(new Set());
                      setFabMenuOpen(false);
                    }}
                    disabled={bulkActionLoading}
                    className="w-full px-4 py-2.5 text-left text-sm text-gray-700 hover:bg-gray-50 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-3"
                  >
                    <X className="w-5 h-5" />
                    <span>Cancelar</span>
                  </button>
                </div>
              </div>
            </div>
          )}
          
          {/* Botão FAB principal */}
          <button
            onClick={() => setFabMenuOpen(!fabMenuOpen)}
            className="w-14 h-14 bg-gradient-to-r from-purple-600 to-purple-700 text-white rounded-full shadow-lg hover:shadow-xl transition-all duration-200 flex items-center justify-center hover:scale-105 active:scale-95"
            aria-label="Ações em massa"
          >
            {fabMenuOpen ? (
              <X className="w-6 h-6" />
            ) : (
              <MoreVertical className="w-6 h-6" />
            )}
          </button>
          
          {/* Badge com contador */}
          <div className="absolute -top-2 -right-2 bg-red-500 text-white text-xs font-bold rounded-full w-6 h-6 flex items-center justify-center">
            {selectedClients.size > 99 ? '99+' : selectedClients.size}
          </div>
        </div>
      )}

      {/* Delete Confirmation Dialog */}
      <ConfirmDialog
        isOpen={deleteConfirm.isOpen}
        onClose={() => setDeleteConfirm({ isOpen: false, clientId: null, clientName: '' })}
        onConfirm={handleDeleteConfirm}
        title="Confirmar Exclusão"
        message={`Tem certeza que deseja excluir o cliente "${deleteConfirm.clientName}"? Esta ação não pode ser desfeita.`}
        confirmText="Excluir"
        cancelText="Cancelar"
        type="danger"
      />

      {/* Bulk Delete Confirmation Dialog */}
      <ConfirmDialog
        isOpen={bulkDeleteConfirm.isOpen}
        onClose={() => setBulkDeleteConfirm({ isOpen: false, count: 0 })}
        onConfirm={handleBulkDeleteConfirm}
        title="Confirmar Exclusão em Lote"
        message={`Tem certeza que deseja excluir ${bulkDeleteConfirm.count} cliente(s)? Esta ação não pode ser desfeita.`}
        confirmText="Excluir"
        cancelText="Cancelar"
        type="danger"
      />

      {/* Edit Client Modal */}
      {editClient && (
        <EditClientModal
          client={editClient}
          servers={servers}
          onClose={() => setEditClient(null)}
          onSuccess={() => {
            setEditClient(null);
            fetchClients();
          }}
        />
      )}
    </Layout>
  );
}

// Edit Client Modal Component
function EditClientModal({ client, servers, onClose, onSuccess }: { client: Client; servers: Server[]; onClose: () => void; onSuccess: () => void }) {
  const originalExpiresAt = client.expires_at ? client.expires_at.split('T')[0] : '';
  const [formData, setFormData] = useState({
    name: client.name,
    username: client.username || '',
    password: '',
    whatsapp: client.whatsapp || '',
    server_id: String(client.server.id),
    expires_at: originalExpiresAt,
    valor_mensalidade: String(client.valor_mensalidade || 0),
    screens: '1',
  });
  const [loading, setLoading] = useState(false);
  const [isRenewal, setIsRenewal] = useState<boolean | null>(null); // null = não alterou data ou não selecionado, true = renovação, false = ajuste
  
  // Verificar se a data foi alterada
  const dateChanged = formData.expires_at !== originalExpiresAt && formData.expires_at !== '' && originalExpiresAt !== '';

  useEffect(() => {
    // Fetch full client data to get screens
    api.get(`/clients/${client.id}`).then(({ data }) => {
      setFormData(prev => ({
        ...prev,
        screens: String(data.screens || 1),
      }));
    }).catch(() => {
      // Ignore error, use default
    });
  }, [client.id]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Se a data foi alterada, verificar se o tipo foi selecionado
    if (dateChanged && isRenewal === null) {
      toast.error('Por favor, selecione o tipo de alteração da data (Renovação ou Ajuste de Data)');
      return;
    }
    
    setLoading(true);

    try {
      // Se a data foi alterada e é renovação, usar o endpoint de renovação
      if (dateChanged && isRenewal === true) {
        await api.post(`/clients/${client.id}/renew`, {
          expires_at: formData.expires_at,
          is_renewal: true
        });
        toast.success('Cliente renovado com sucesso!');
      } else {
        // Caso contrário, atualizar normalmente (incluindo ajuste de data)
        const payload = {
          ...formData,
          valor_mensalidade: parseFloat(formData.valor_mensalidade) || 0,
          screens: parseInt(formData.screens) || 1,
        };

        await api.put(`/clients/${client.id}`, payload);
        toast.success('Cliente atualizado com sucesso!');
      }
      
      onSuccess();
    } catch (error: any) {
      console.error('Error updating client:', error);
      toast.error(error.response?.data?.message || 'Erro ao atualizar cliente. Verifique os dados e tente novamente.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div
      className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-3 sm:p-4"
      onClick={(e) => {
        if (e.target === e.currentTarget) {
          onClose();
        }
      }}
    >
      <div className="bg-white rounded-xl sm:rounded-2xl w-full max-w-4xl max-h-[95vh] sm:max-h-[90vh] flex flex-col shadow-2xl m-2 sm:m-0">
        {/* Header */}
        <div className="flex justify-between items-center p-4 sm:p-6 border-b border-gray-200 flex-shrink-0">
          <h2 className="text-xl sm:text-2xl font-bold text-gray-800 truncate pr-2">Editar Cliente</h2>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 text-2xl flex-shrink-0"
            aria-label="Fechar"
          >
            ×
          </button>
        </div>

        {/* Content - Scrollable */}
        <div className="overflow-y-auto flex-1 p-4 sm:p-6">
          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Nome */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Nome *
              </label>
              <input
                type="text"
                required
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                placeholder="Nome do cliente"
              />
            </div>

            {/* Servidor */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Servidor *
              </label>
              <select
                required
                value={formData.server_id}
                onChange={(e) => setFormData({ ...formData, server_id: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
              >
                <option value="">Selecione um servidor</option>
                {servers.filter(server => server.active).map((server) => (
                  <option key={server.id} value={server.id}>
                    {server.name}
                  </option>
                ))}
              </select>
            </div>

            {/* Usuário */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Usuário
              </label>
              <input
                type="text"
                value={formData.username}
                onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                placeholder="usuário"
              />
            </div>

            {/* Senha */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Senha
              </label>
              <input
                type="text"
                value={formData.password}
                onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                placeholder="senha (deixe vazio para não alterar)"
              />
            </div>

            {/* WhatsApp */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                WhatsApp
              </label>
              <input
                type="text"
                value={formData.whatsapp}
                onChange={(e) => setFormData({ ...formData, whatsapp: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                placeholder="5511999999999"
              />
            </div>

            {/* Data de Vencimento */}
            <div>
              <DatePicker
                label="Data de Vencimento"
                value={formData.expires_at}
                onChange={(value) => {
                  setFormData({ ...formData, expires_at: value });
                  // Reset isRenewal quando a data mudar
                  setIsRenewal(null);
                }}
              />
              {dateChanged && (
                <div className="mt-4 p-4 bg-yellow-50 border border-yellow-200 rounded-lg">
                  <label className="block text-sm font-medium text-gray-700 mb-3">
                    Tipo de Alteração da Data:
                  </label>
                  <div className="space-y-2">
                    <label className="flex items-center space-x-3 cursor-pointer">
                      <input
                        type="radio"
                        name="date_change_type"
                        value="renewal"
                        checked={isRenewal === true}
                        onChange={() => setIsRenewal(true)}
                        className="w-4 h-4 text-blue-600 focus:ring-blue-500"
                      />
                      <div>
                        <span className="text-sm font-medium text-gray-900">Renovação</span>
                        <p className="text-xs text-gray-500">Consome créditos do servidor baseado no número de telas</p>
                      </div>
                    </label>
                    <label className="flex items-center space-x-3 cursor-pointer">
                      <input
                        type="radio"
                        name="date_change_type"
                        value="adjustment"
                        checked={isRenewal === false}
                        onChange={() => setIsRenewal(false)}
                        className="w-4 h-4 text-blue-600 focus:ring-blue-500"
                      />
                      <div>
                        <span className="text-sm font-medium text-gray-900">Ajuste de Data</span>
                        <p className="text-xs text-gray-500">Apenas altera a data sem consumir créditos (útil para correções)</p>
                      </div>
                    </label>
                  </div>
                </div>
              )}
            </div>

            {/* Valor */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Valor Mensal (R$)
              </label>
              <input
                type="number"
                step="0.01"
                value={formData.valor_mensalidade}
                onChange={(e) => setFormData({ ...formData, valor_mensalidade: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                placeholder="0.00"
              />
            </div>

            {/* Número de Telas */}
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">
                Número de Telas
              </label>
              <input
                type="number"
                min="1"
                max="10"
                value={formData.screens}
                onChange={(e) => setFormData({ ...formData, screens: e.target.value })}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                placeholder="1"
              />
            </div>
          </form>
        </div>

        {/* Footer */}
        <div className="flex flex-col sm:flex-row gap-2 sm:gap-3 p-4 sm:p-6 border-t border-gray-200 bg-gray-50 rounded-b-xl sm:rounded-b-2xl flex-shrink-0">
          <button
            type="button"
            onClick={onClose}
            className="flex-1 px-4 sm:px-6 py-2 sm:py-3 border border-gray-300 rounded-lg text-gray-700 font-medium hover:bg-gray-100 transition-colors text-sm sm:text-base"
          >
            Cancelar
          </button>
          <button
            type="submit"
            onClick={handleSubmit}
            disabled={loading}
            className="flex-1 px-4 sm:px-6 py-2 sm:py-3 rounded-lg text-white font-medium transition-colors disabled:opacity-50 text-sm sm:text-base"
            style={{ backgroundColor: '#7C3AED' }}
          >
            {loading ? 'Salvando...' : 'Atualizar Cliente'}
          </button>
        </div>
      </div>
    </div>
  );
}
