import { useEffect, useState, useRef } from 'react';
import { Link } from 'react-router-dom';
import { Layout } from '../components/Layout';
import { VariableSelector } from '../components/VariableSelector';
import { toast } from '../components/Toast';
import { ConfirmDialog } from '../components/ConfirmDialog';
import api from '../lib/api';

interface Server {
  id: number;
  name: string;
  contact_name?: string;
  contact_whatsapp?: string;
  panel_url?: string;
  panel_username?: string;
  panel_password?: string;
  active: boolean;
  clients_count?: number;
  credits_balance?: number;
}

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: 'welcome',
    title: 'Boas-vindas',
    content: 'Olá! Bem-vindo ao servidor {nome}.\n\n🌐 Acesse: {painel_url}\n👤 Usuário: {painel_usuario}\n🔐 Senha: {painel_senha}\n\n📱 Contato: {contato_nome}\n💬 WhatsApp: {contato_whatsapp}'
  },
  {
    id: 'credentials',
    title: 'Enviar Credenciais',
    content: 'Credenciais de acesso ao painel {nome}:\n\n🌐 URL: {painel_url}\n👤 Usuário: {painel_usuario}\n🔐 Senha: {painel_senha}\n\nQualquer dúvida, entre em contato!'
  },
  {
    id: 'maintenance',
    title: 'Manutenção',
    content: 'Atenção! O servidor {nome} entrará em manutenção.\n\nContato: {contato_nome}\nWhatsApp: {contato_whatsapp}'
  },
  {
    id: 'custom',
    title: 'Mensagem Personalizada',
    content: ''
  }
];

export function ServersPage() {
  const [servers, setServers] = useState<Server[]>([]);
  const [loading, setLoading] = useState(true);
  const [showPurchaseModal, setShowPurchaseModal] = useState(false);
  const [selectedServerId, setSelectedServerId] = useState<number | null>(null);
  const [quantity, setQuantity] = useState('');
  const [unitPrice, setUnitPrice] = useState('');
  const [description, setDescription] = useState('');
  const [notes, setNotes] = useState('');
  const [submitting, setSubmitting] = useState(false);
  const [whatsappModal, setWhatsappModal] = useState<Server | null>(null);
  const [migrateModal, setMigrateModal] = useState<Server | null>(null);
  const [deleteModal, setDeleteModal] = useState<Server | null>(null);
  const [deleteTargetServerId, setDeleteTargetServerId] = useState('');
  const [selectedTemplate, setSelectedTemplate] = useState('custom');
  const [customMessage, setCustomMessage] = useState('');
  const [templates, setTemplates] = useState<Array<{ id: number; name: string; content: string }>>([]);
  const [targetServerId, setTargetServerId] = useState('');
  const [migrating, setMigrating] = useState(false);
  const [deleting, setDeleting] = useState(false);
  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);

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

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

  useEffect(() => {
    if (whatsappModal && selectedTemplate !== 'custom') {
      const templateId = parseInt(selectedTemplate);
      const template = templates.find(t => t.id === templateId);
      if (template) {
        setCustomMessage(replaceVariables(template.content, whatsappModal));
      }
    }
  }, [selectedTemplate, whatsappModal, templates]);

  const fetchServers = async () => {
    try {
      const { data } = await api.get('/servers');
      setServers(data.servers || []);
    } catch (error) {
      console.error('Failed to fetch servers:', error);
    } finally {
      setLoading(false);
    }
  };

  const [confirmDialog, setConfirmDialog] = useState<{
    show: boolean;
    title: string;
    message: string;
    onConfirm: () => void;
  }>({ show: false, title: '', message: '', onConfirm: () => {} });

  const handleToggleStatus = async (server: Server) => {
    setConfirmDialog({
      show: true,
      title: server.active ? 'Suspender Servidor' : 'Ativar Servidor',
      message: `Deseja ${server.active ? 'suspender' : 'ativar'} o servidor "${server.name}"?`,
      onConfirm: async () => {
        try {
          await api.put(`/servers/${server.id}`, {
            active: !server.active
          });
          toast.success(`Servidor ${!server.active ? 'ativado' : 'suspenso'} com sucesso!`);
          fetchServers();
        } catch (error) {
          console.error('Error toggling server status:', error);
          toast.error('Erro ao alterar status do servidor');
        }
        setConfirmDialog({ show: false, title: '', message: '', onConfirm: () => {} });
      }
    });
  };

  const handleDelete = async (server: Server) => {
    // Se o servidor tem clientes, obrigar migração antes de excluir
    if (server.clients_count && server.clients_count > 0) {
      setDeleteModal(server);
      setDeleteTargetServerId('');
      return;
    }

    // Se não tem clientes, pode excluir diretamente
    setConfirmDialog({
      show: true,
      title: 'Excluir Servidor',
      message: `Tem certeza que deseja excluir o servidor "${server.name}"?\n\nEsta ação não pode ser desfeita.`,
      onConfirm: async () => {
        try {
          await api.delete(`/servers/${server.id}`);
          toast.success('Servidor excluído com sucesso!');
          fetchServers();
        } catch (error) {
          console.error('Error deleting server:', error);
          toast.error('Erro ao excluir servidor');
        }
        setConfirmDialog({ show: false, title: '', message: '', onConfirm: () => {} });
      }
    });
  };

  const handleDeleteWithMigration = async () => {
    if (!deleteModal || !deleteTargetServerId) {
      toast.error('Selecione o servidor de destino para migrar os clientes');
      return;
    }

    if (deleteModal.id === parseInt(deleteTargetServerId)) {
      toast.error('O servidor de destino deve ser diferente do servidor atual');
      return;
    }

    const targetServer = servers.find(s => s.id === parseInt(deleteTargetServerId));
    if (!targetServer) {
      toast.error('Servidor de destino não encontrado');
      return;
    }

    setDeleting(true);
    try {
      // Primeiro, migrar os clientes
      await api.post(`/servers/${deleteModal.id}/migrate-clients`, {
        target_server_id: parseInt(deleteTargetServerId)
      });
      
      // Depois, excluir o servidor
      await api.delete(`/servers/${deleteModal.id}`);
      
      toast.success(`Clientes migrados e servidor "${deleteModal.name}" excluído com sucesso!`);
      setDeleteModal(null);
      setDeleteTargetServerId('');
      fetchServers();
    } catch (error: any) {
      console.error('Error deleting server with migration:', error);
      const errorMessage = error.response?.data?.message || 'Erro ao migrar clientes e excluir servidor';
      toast.error(errorMessage);
    } finally {
      setDeleting(false);
    }
  };

  const handlePurchase = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!selectedServerId || !quantity || parseInt(quantity) <= 0) {
      toast.error('Selecione um servidor e informe uma quantidade válida');
      return;
    }

    setSubmitting(true);

    try {
      await api.post('/recharges/purchase', {
        server_id: selectedServerId,
        quantity: parseInt(quantity),
        unit_price: unitPrice ? parseFloat(unitPrice) : 0,
        description: description || undefined,
        notes: notes || undefined,
      });

      toast.success('Créditos adicionados com sucesso!');
      setShowPurchaseModal(false);
      setSelectedServerId(null);
      setQuantity('');
      setUnitPrice('');
      setDescription('');
      setNotes('');
      fetchServers();
    } catch (error: unknown) {
      console.error('Erro ao comprar créditos:', error);
      const axiosError = error as { response?: { data?: { message?: string } } };
      const message = axiosError?.response?.data?.message || 'Erro ao adicionar créditos';
      toast.error(message);
    } finally {
      setSubmitting(false);
    }
  };

  const replaceVariables = (message: string, server: Server): string => {
    return message
      .replace(/{nome}/g, server.name)
      .replace(/{contato_nome}/g, server.contact_name || 'N/A')
      .replace(/{contato_whatsapp}/g, server.contact_whatsapp || 'N/A')
      .replace(/{painel_url}/g, server.panel_url || 'N/A')
      .replace(/{painel_usuario}/g, server.panel_username || 'N/A')
      .replace(/{painel_senha}/g, server.panel_password || 'N/A');
  };

  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 handleSendWhatsApp = async () => {
    if (!whatsappModal || !whatsappModal.contact_whatsapp) {
      toast.error('Este servidor não possui WhatsApp cadastrado');
      return;
    }
    
    if (!selectedInstance) {
      toast.error('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);

    const whatsappNumber = whatsappModal.contact_whatsapp.replace(/\D/g, '');
    
    try {
      setSendingMessage(true);
      
      await api.post('/whatsapp/send-message', {
        to_number: whatsappNumber,
        message: message,
        connection_id: selectedInstance
      });
      
      toast.success('Mensagem enviada com sucesso!');
      setWhatsappModal(null);
    } 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 handleMigrateClients = async () => {
    if (!migrateModal || !targetServerId) {
      toast.error('Selecione o servidor de destino');
      return;
    }

    if (migrateModal.id === parseInt(targetServerId)) {
      toast.error('O servidor de destino deve ser diferente do servidor atual');
      return;
    }

    const targetServer = servers.find(s => s.id === parseInt(targetServerId));
    setConfirmDialog({
      show: true,
      title: 'Migrar Clientes',
      message: `Migrar ${migrateModal.clients_count || 0} cliente(s) de "${migrateModal.name}" para "${targetServer?.name}"?\n\nEsta ação atualizará todos os clientes.`,
      onConfirm: async () => {
        setMigrating(true);
        try {
          await api.post(`/servers/${migrateModal.id}/migrate-clients`, {
            target_server_id: parseInt(targetServerId)
          });
          toast.success('Clientes migrados com sucesso!');
          setMigrateModal(null);
          setTargetServerId('');
          fetchServers();
        } catch (error: any) {
          console.error('Error migrating clients:', error);
          const errorMessage = error.response?.data?.message || 'Erro ao migrar clientes';
          toast.error(errorMessage);
        } finally {
          setMigrating(false);
          setConfirmDialog({ show: false, title: '', message: '', onConfirm: () => {} });
        }
      }
    });
  };

  if (loading) {
    return (
      <Layout title="Servidores">
        <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="Servidores">
      <div className="mb-6 flex items-center justify-end">
        <Link to="/servers/new" className="btn-primary">
          <span className="flex items-center">
            <svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
            </svg>
            Novo Servidor
          </span>
        </Link>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        {servers.map((server) => (
          <div key={server.id} className="card hover:shadow-card-hover transition-all flex flex-col">
            <div className="flex items-center justify-between mb-4">
              <div className="flex items-center space-x-3">
                <div className="w-12 h-12 bg-gradient-to-br from-primary-blue to-primary-purple rounded-2xl flex items-center justify-center">
                  <svg className="w-6 h-6 text-white" fill="currentColor" viewBox="0 0 24 24">
                    <path d="M20 13H4c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h16c.55 0 1-.45 1-1v-6c0-.55-.45-1-1-1zM7 19c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zM20 3H4c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h16c.55 0 1-.45 1-1V4c0-.55-.45-1-1-1zM7 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z" />
                  </svg>
                </div>
                <div>
                  <h3 className="font-bold text-text-title">{server.name}</h3>
                  {server.contact_name && (
                    <p className="text-sm text-text-secondary">{server.contact_name}</p>
                  )}
                </div>
              </div>
              <span className={`px-3 py-1 rounded-full text-xs font-semibold ${
                server.active ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800'
              }`}>
                {server.active ? 'Ativo' : 'Inativo'}
              </span>
            </div>
            
            <div className="space-y-2 mb-4">
              {server.contact_name && (
                <div className="flex items-center text-sm">
                  <span className="text-text-secondary w-20">Contato:</span>
                  <span className="text-text-normal font-medium">{server.contact_name}</span>
                </div>
              )}
              {server.contact_whatsapp && (
                <div className="flex items-center text-sm">
                  <span className="text-text-secondary w-20">WhatsApp:</span>
                  <span className="text-text-normal font-medium">{server.contact_whatsapp}</span>
                </div>
              )}
              <div className="flex items-center text-sm">
                <span className="text-text-secondary w-20">Clientes:</span>
                <span className="text-text-normal font-medium">{server.clients_count || 0}</span>
              </div>
              <div className="flex items-center text-sm">
                <span className="text-text-secondary w-32">Créditos disponíveis:</span>
                <span className={`font-semibold ${(server.credits_balance || 0) < 10 ? 'text-red-600' : 'text-green-600'}`}>
                  {server.credits_balance || 0}
                </span>
              </div>
            </div>
            
            <div className="flex-grow"></div>
            
            <div className="pt-4 border-t border-gray-100 mt-4">
              <div className="flex items-center justify-between gap-2">
                {/* Editar */}
                <Link
                  to={`/servers/${server.id}`}
                  className="text-blue-600 hover:text-blue-800 p-2 rounded hover:bg-blue-50 transition-colors flex-shrink-0"
                  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>
                </Link>

                {/* Comprar Créditos (antes era "Gerenciar") */}
                <button
                  onClick={() => {
                    setSelectedServerId(server.id);
                    setShowPurchaseModal(true);
                  }}
                  className="p-2 rounded transition-colors flex-shrink-0"
                  style={{ color: '#7C3AED' }}
                  title="Comprar Créditos"
                  onMouseEnter={(e) => e.currentTarget.style.backgroundColor = 'rgba(124, 58, 237, 0.1)'}
                  onMouseLeave={(e) => e.currentTarget.style.backgroundColor = 'transparent'}
                >
                  <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                </button>

                {/* Suspender/Ativar */}
                <button
                  onClick={() => handleToggleStatus(server)}
                  className={`${server.active ? 'text-yellow-600 hover:text-yellow-800 hover:bg-yellow-50' : 'text-green-600 hover:text-green-800 hover:bg-green-50'} p-2 rounded transition-colors flex-shrink-0`}
                  title={server.active ? 'Suspender' : 'Ativar'}
                >
                  {server.active ? (
                    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                    </svg>
                  ) : (
                    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 11V7a4 4 0 118 0m-4 8v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2z" />
                    </svg>
                  )}
                </button>

                {/* Migrar Clientes */}
                <button
                  onClick={() => setMigrateModal(server)}
                  className="text-purple-600 hover:text-purple-800 p-2 rounded hover:bg-purple-50 transition-colors flex-shrink-0"
                  title="Migrar Clientes"
                >
                  <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" />
                  </svg>
                </button>

                {/* WhatsApp */}
                {connectedInstances.length > 0 && (
                  <button
                    onClick={() => setWhatsappModal(server)}
                    className="text-emerald-600 hover:text-emerald-800 p-2 rounded hover:bg-emerald-50 transition-colors flex-shrink-0"
                    title="Enviar 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={() => handleDelete(server)}
                  className="text-red-600 hover:text-red-800 p-2 rounded hover:bg-red-50 transition-colors flex-shrink-0"
                  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>
            </div>
          </div>
        ))}
      </div>

      {servers.length === 0 && (
        <div className="card 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="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>
          <p className="mt-4 text-sm text-text-secondary">Nenhum servidor configurado</p>
        </div>
      )}

      {/* Modal WhatsApp */}
      {whatsappModal && (
        <div 
          className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
          onClick={(e) => {
            if (e.target === e.currentTarget) {
              setWhatsappModal(null);
            }
          }}
        >
          <div className="bg-white rounded-2xl w-full max-w-2xl shadow-2xl">
            <div className="flex justify-between items-center p-6 border-b border-gray-200">
              <h3 className="text-xl font-bold text-gray-800">Enviar WhatsApp - {whatsappModal.name}</h3>
              <button
                onClick={() => setWhatsappModal(null)}
                className="text-gray-400 hover:text-gray-600 text-2xl"
              >
                ×
              </button>
            </div>

            <div className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  WhatsApp de Contato
                </label>
                <input
                  type="text"
                  value={whatsappModal.contact_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 && selectedTemplate === 'custom' && (
                  <VariableSelector
                    textareaRef={messageTextareaRef}
                    value={customMessage}
                    onChange={setCustomMessage}
                    label="Mensagem"
                    customVariables={[
                      {
                        category: 'Servidor',
                        items: [
                          { key: 'nome', label: 'Nome do Servidor', example: whatsappModal.name },
                          { key: 'contato_nome', label: 'Nome do Contato', example: whatsappModal.contact_name || 'N/A' },
                          { key: 'contato_whatsapp', label: 'WhatsApp do Contato', example: whatsappModal.contact_whatsapp || 'N/A' },
                          { key: 'painel_url', label: 'URL do Painel', example: whatsappModal.panel_url || 'N/A' },
                          { key: 'painel_usuario', label: 'Usuário do Painel', example: whatsappModal.panel_username || 'N/A' },
                          { key: 'painel_senha', label: 'Senha do Painel', example: whatsappModal.panel_password || '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={6}
                  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 gap-3 p-6 border-t border-gray-200 bg-gray-50 rounded-b-2xl">
              <button
                type="button"
                onClick={() => setWhatsappModal(null)}
                className="flex-1 px-6 py-3 border border-gray-300 rounded-lg text-gray-700 font-medium hover:bg-gray-100 transition-colors"
              >
                Cancelar
              </button>
              <button
                type="button"
                onClick={handleSendWhatsApp}
                disabled={!whatsappModal.contact_whatsapp || !selectedInstance || sendingMessage}
                className="flex-1 px-6 py-3 bg-emerald-600 text-white rounded-lg font-medium hover:bg-emerald-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              >
                {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...
                  </>
                ) : (
                  <>
                    Enviar WhatsApp
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Modal Migrar Clientes */}
      {migrateModal && (
        <div 
          className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
          onClick={(e) => {
            if (e.target === e.currentTarget) {
              setMigrateModal(null);
              setTargetServerId('');
            }
          }}
        >
          <div className="bg-white rounded-2xl w-full max-w-lg shadow-2xl">
            <div className="flex justify-between items-center p-6 border-b border-gray-200">
              <h3 className="text-xl font-bold text-gray-800">Migrar Clientes</h3>
              <button
                onClick={() => {
                  setMigrateModal(null);
                  setTargetServerId('');
                }}
                className="text-gray-400 hover:text-gray-600 text-2xl"
              >
                ×
              </button>
            </div>

            <div className="p-6 space-y-4">
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Servidor Origem
                </label>
                <input
                  type="text"
                  value={`${migrateModal.name} (${migrateModal.clients_count || 0} clientes)`}
                  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">
                  Servidor Destino *
                </label>
                <select
                  value={targetServerId}
                  onChange={(e) => setTargetServerId(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 o servidor destino</option>
                  {servers
                    .filter(s => s.id !== migrateModal.id && s.active)
                    .map(server => (
                      <option key={server.id} value={server.id}>
                        {server.name} ({server.clients_count || 0} clientes)
                      </option>
                    ))}
                </select>
                <p className="mt-2 text-xs text-gray-500">
                  ⚠️ Todos os {migrateModal.clients_count || 0} cliente(s) serão transferidos para o servidor selecionado.
                </p>
              </div>
            </div>

            <div className="flex gap-3 p-6 border-t border-gray-200 bg-gray-50 rounded-b-2xl">
              <button
                type="button"
                onClick={() => {
                  setMigrateModal(null);
                  setTargetServerId('');
                }}
                className="flex-1 px-6 py-3 border border-gray-300 rounded-lg text-gray-700 font-medium hover:bg-gray-100 transition-colors"
              >
                Cancelar
              </button>
              <button
                type="button"
                onClick={handleMigrateClients}
                disabled={!targetServerId || migrating}
                className="flex-1 px-6 py-3 bg-purple-600 text-white rounded-lg font-medium hover:bg-purple-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {migrating ? 'Migrando...' : 'Migrar Clientes'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Modal Excluir Servidor com Migração Obrigatória */}
      {deleteModal && (
        <div 
          className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4"
          onClick={(e) => {
            if (e.target === e.currentTarget) {
              setDeleteModal(null);
              setDeleteTargetServerId('');
            }
          }}
        >
          <div className="bg-white rounded-2xl w-full max-w-lg shadow-2xl">
            <div className="flex justify-between items-center p-6 border-b border-gray-200">
              <h3 className="text-xl font-bold text-gray-800">Excluir Servidor</h3>
              <button
                onClick={() => {
                  setDeleteModal(null);
                  setDeleteTargetServerId('');
                }}
                className="text-gray-400 hover:text-gray-600 text-2xl"
              >
                ×
              </button>
            </div>

            <div className="p-6 space-y-4">
              <div className="bg-red-50 border border-red-200 rounded-lg p-4">
                <p className="text-sm text-red-800 font-medium mb-2">
                  ⚠️ Este servidor possui {deleteModal.clients_count || 0} cliente(s) vinculado(s).
                </p>
                <p className="text-sm text-red-700">
                  Para excluir este servidor, você <strong>deve</strong> transferir todos os clientes para outro servidor.
                </p>
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-700 mb-1">
                  Servidor a Excluir
                </label>
                <input
                  type="text"
                  value={`${deleteModal.name} (${deleteModal.clients_count || 0} clientes)`}
                  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">
                  Servidor Destino para Migração * <span className="text-red-600">(Obrigatório)</span>
                </label>
                <select
                  value={deleteTargetServerId}
                  onChange={(e) => setDeleteTargetServerId(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"
                  required
                >
                  <option value="">Selecione um servidor...</option>
                  {servers
                    .filter(server => server.id !== deleteModal.id && server.active)
                    .map(server => (
                      <option key={server.id} value={server.id}>
                        {server.name} ({server.clients_count || 0} clientes)
                      </option>
                    ))}
                </select>
                {deleteTargetServerId && (
                  <p className="mt-2 text-sm text-orange-600">
                    ⚠️ Todos os {deleteModal.clients_count || 0} cliente(s) serão transferidos para o servidor selecionado antes da exclusão.
                  </p>
                )}
              </div>
            </div>

            <div className="flex gap-3 p-6 border-t border-gray-200 bg-gray-50 rounded-b-2xl">
              <button
                type="button"
                onClick={() => {
                  setDeleteModal(null);
                  setDeleteTargetServerId('');
                }}
                className="flex-1 px-6 py-3 border border-gray-300 rounded-lg text-gray-700 font-medium hover:bg-gray-100 transition-colors"
              >
                Cancelar
              </button>
              <button
                type="button"
                onClick={handleDeleteWithMigration}
                disabled={!deleteTargetServerId || deleting}
                className="flex-1 px-6 py-3 bg-red-600 text-white rounded-lg font-medium hover:bg-red-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {deleting ? 'Migrando e Excluindo...' : 'Migrar e Excluir'}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Modal Comprar Créditos */}
      {showPurchaseModal && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4 overflow-y-auto">
          <div className="bg-white rounded-2xl w-full max-w-md shadow-2xl flex flex-col max-h-[95vh] my-4">
            <div className="flex justify-between items-center p-6 border-b border-gray-200 flex-shrink-0">
              <h2 className="text-xl font-bold text-gray-800">Comprar Créditos</h2>
              <button
                onClick={() => {
                  setShowPurchaseModal(false);
                  setSelectedServerId(null);
                  setQuantity('');
                  setUnitPrice('');
                  setDescription('');
                  setNotes('');
                }}
                className="text-gray-400 hover:text-gray-600 text-2xl"
              >
                ×
              </button>
            </div>

            <div className="overflow-y-auto flex-1">
              <form onSubmit={handlePurchase} className="p-6 space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Servidor *
                  </label>
                  <input
                    type="text"
                    value={servers.find(s => s.id === selectedServerId)?.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">
                    Quantidade de Créditos *
                  </label>
                  <input
                    type="number"
                    required
                    min="1"
                    value={quantity}
                    onChange={(e) => setQuantity(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="Ex: 100"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Valor Unitário (R$)
                  </label>
                  <input
                    type="number"
                    step="0.01"
                    min="0"
                    value={unitPrice}
                    onChange={(e) => setUnitPrice(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="Ex: 1.50"
                  />
                  {quantity && unitPrice && (
                    <p className="mt-1 text-sm text-gray-600">
                      Total: R$ {(parseFloat(quantity) * parseFloat(unitPrice)).toFixed(2)}
                    </p>
                  )}
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Descrição
                  </label>
                  <input
                    type="text"
                    value={description}
                    onChange={(e) => setDescription(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="Ex: Compra de 100 créditos"
                  />
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">
                    Observações
                  </label>
                  <textarea
                    value={notes}
                    onChange={(e) => setNotes(e.target.value)}
                    rows={3}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent resize-none"
                    placeholder="Observações adicionais..."
                  />
                </div>
                
                <div className="flex gap-3 pt-4 border-t border-gray-200 mt-4">
                  <button
                    type="button"
                    onClick={() => {
                      setShowPurchaseModal(false);
                      setSelectedServerId(null);
                      setQuantity('');
                      setUnitPrice('');
                      setDescription('');
                      setNotes('');
                    }}
                    className="flex-1 px-6 py-2.5 border border-gray-300 rounded-lg text-gray-700 font-medium hover:bg-gray-50 transition-colors"
                  >
                    Cancelar
                  </button>
                  <button
                    type="submit"
                    disabled={submitting}
                    className="flex-1 px-6 py-2.5 rounded-lg text-white font-medium transition-colors disabled:opacity-50 shadow-md"
                    style={{ backgroundColor: '#7C3AED' }}
                  >
                    {submitting ? 'Comprando...' : 'Comprar'}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}

      <ConfirmDialog
        isOpen={confirmDialog.show}
        title={confirmDialog.title}
        message={confirmDialog.message}
        onConfirm={confirmDialog.onConfirm}
        onClose={() => setConfirmDialog({ show: false, title: '', message: '', onConfirm: () => {} })}
      />
    </Layout>
  );
}
