import React, { useState, useEffect } from 'react';
import { FiPlus, FiEdit2, FiTrash2, FiCheckCircle, FiXCircle, FiActivity } from 'react-icons/fi';
import { Layout } from '../components/Layout';
import api from '../lib/api';
import WhatsAppIntegrationModal from '../components/WhatsAppIntegrationModal';

interface WhatsAppIntegration {
  id: number;
  name: string;
  provider: 'evolution' | 'uazapi' | 'evolutiongo';
  api_url: string;
  api_key: string;
  max_users: number;
  current_users: number;
  status: 'active' | 'inactive' | 'error';
  created_at: string;
}

interface Statistics {
  total_integrations: number;
  active_integrations: number;
  total_capacity: number;
  total_connections: number;
  available_slots: number;
  usage_percentage: number;
  by_provider: {
    evolution: number;
    uazapi: number;
    evolutiongo?: number;
  };
}

const WhatsAppIntegrationsPage: React.FC = () => {
  const [integrations, setIntegrations] = useState<WhatsAppIntegration[]>([]);
  const [statistics, setStatistics] = useState<Statistics | null>(null);
  const [loading, setLoading] = useState(true);
  const [modalOpen, setModalOpen] = useState(false);
  const [editingIntegration, setEditingIntegration] = useState<WhatsAppIntegration | null>(null);

  const fetchIntegrations = async () => {
    try {
      const { data } = await api.get('/admin/whatsapp/integrations');
      setIntegrations(data.integrations);
    } catch (error) {
      console.error('Failed to fetch integrations:', error);
    }
  };

  const fetchStatistics = async () => {
    try {
      const { data } = await api.get('/admin/whatsapp/statistics');
      setStatistics(data);
    } catch (error) {
      console.error('Failed to fetch statistics:', error);
    }
  };

  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      await Promise.all([fetchIntegrations(), fetchStatistics()]);
      setLoading(false);
    };
    loadData();
  }, []);

  const handleAdd = () => {
    setEditingIntegration(null);
    setModalOpen(true);
  };

  const handleEdit = (integration: WhatsAppIntegration) => {
    setEditingIntegration(integration);
    setModalOpen(true);
  };

  const handleDelete = async (id: number) => {
    if (!confirm('Tem certeza que deseja excluir esta integração?')) return;

    try {
      await api.delete(`/admin/whatsapp/integrations/${id}`);
      await fetchIntegrations();
      await fetchStatistics();
    } catch (error: any) {
      alert(error.response?.data?.message || 'Erro ao excluir integração');
    }
  };

  const handleTest = async (id: number) => {
    try {
      await api.post(`/admin/whatsapp/integrations/${id}/test`);
      alert('Conexão testada com sucesso!');
    } catch (error: any) {
      alert(error.response?.data?.message || 'Falha ao testar conexão');
    }
  };

  const handleModalClose = async (success: boolean) => {
    setModalOpen(false);
    setEditingIntegration(null);
    if (success) {
      await fetchIntegrations();
      await fetchStatistics();
    }
  };

  const getStatusBadge = (status: string) => {
    const styles = {
      active: 'bg-green-100 text-green-800',
      inactive: 'bg-gray-100 text-gray-800',
      error: 'bg-red-100 text-red-800',
    };
    return (
      <span className={`px-2 py-1 rounded-full text-xs font-medium ${styles[status as keyof typeof styles]}`}>
        {status === 'active' && <FiCheckCircle className="inline mr-1" />}
        {status === 'error' && <FiXCircle className="inline mr-1" />}
        {status.toUpperCase()}
      </span>
    );
  };

  const getProviderBadge = (provider: string) => {
    return (
      <span className="px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
        {provider.toUpperCase()}
      </span>
    );
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center h-96">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-purple-600"></div>
      </div>
    );
  }

  return (
    <Layout title="Integrações WhatsApp">
      <div className="space-y-6">
        <div className="flex justify-between items-center">
          <h1 className="text-3xl font-bold text-gray-900">Integrações WhatsApp</h1>
          <button
            onClick={handleAdd}
            className="flex items-center gap-2 bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700 transition"
          >
            <FiPlus /> Nova Integração
          </button>
        </div>

        {/* Statistics Cards */}
        {statistics && (
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
            <div className="bg-white p-6 rounded-lg shadow">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-600">Total de Integrações</p>
                  <p className="text-2xl font-bold text-gray-900">{statistics.total_integrations}</p>
                </div>
                <FiActivity className="text-purple-600 text-3xl" />
              </div>
            </div>

            <div className="bg-white p-6 rounded-lg shadow">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-600">Integrações Ativas</p>
                  <p className="text-2xl font-bold text-green-600">{statistics.active_integrations}</p>
                </div>
                <FiCheckCircle className="text-green-600 text-3xl" />
              </div>
            </div>

            <div className="bg-white p-6 rounded-lg shadow">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-600">Conexões Ativas</p>
                  <p className="text-2xl font-bold text-blue-600">
                    {statistics.total_connections} / {statistics.total_capacity}
                  </p>
                </div>
                <div className="text-sm text-gray-500">{statistics.usage_percentage}%</div>
              </div>
              <div className="mt-2 w-full bg-gray-200 rounded-full h-2">
                <div
                  className="bg-blue-600 h-2 rounded-full"
                  style={{ width: `${statistics.usage_percentage}%` }}
                ></div>
              </div>
            </div>

            <div className="bg-white p-6 rounded-lg shadow">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-sm text-gray-600">Slots Disponíveis</p>
                  <p className="text-2xl font-bold text-purple-600">{statistics.available_slots}</p>
                </div>
                <div className="text-xs text-gray-500 space-y-1">
                  <div>Evolution: {statistics.by_provider.evolution}</div>
                  <div>Uazapi: {statistics.by_provider.uazapi}</div>
                  <div>EvolutionGO: {statistics.by_provider.evolutiongo ?? 0}</div>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Integrations Table */}
        <div className="bg-white rounded-lg shadow overflow-hidden">
          <table className="min-w-full divide-y divide-gray-200">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Nome
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Provedor
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Status
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Capacidade
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Uso
                </th>
                <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                  Ações
                </th>
              </tr>
            </thead>
            <tbody className="bg-white divide-y divide-gray-200">
              {integrations.length === 0 ? (
                <tr>
                  <td colSpan={6} className="px-6 py-8 text-center text-gray-500">
                    Nenhuma integração cadastrada. Clique em "Nova Integração" para adicionar.
                  </td>
                </tr>
              ) : (
                integrations.map((integration) => (
                  <tr key={integration.id} className="hover:bg-gray-50">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="font-medium text-gray-900">{integration.name}</div>
                      <div className="text-sm text-gray-500">{integration.api_url}</div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      {getProviderBadge(integration.provider)}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      {getStatusBadge(integration.status)}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                      {integration.max_users} usuários
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center">
                        <span className="text-sm font-medium text-gray-900">
                          {integration.current_users} / {integration.max_users}
                        </span>
                        <div className="ml-2 w-20 bg-gray-200 rounded-full h-2">
                          <div
                            className={`h-2 rounded-full ${integration.current_users >= integration.max_users
                              ? 'bg-red-600'
                              : 'bg-green-600'
                              }`}
                            style={{
                              width: `${Math.min(
                                (integration.current_users / integration.max_users) * 100,
                                100
                              )}%`,
                            }}
                          ></div>
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <button
                        onClick={() => handleTest(integration.id)}
                        className="text-blue-600 hover:text-blue-900 mr-3"
                        title="Testar conexão"
                      >
                        <FiActivity className="inline" />
                      </button>
                      <button
                        onClick={() => handleEdit(integration)}
                        className="text-indigo-600 hover:text-indigo-900 mr-3"
                        title="Editar"
                      >
                        <FiEdit2 className="inline" />
                      </button>
                      <button
                        onClick={() => handleDelete(integration.id)}
                        className="text-red-600 hover:text-red-900"
                        title="Excluir"
                        disabled={integration.current_users > 0}
                      >
                        <FiTrash2 className="inline" />
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {modalOpen && (
          <WhatsAppIntegrationModal
            integration={editingIntegration}
            onClose={handleModalClose}
          />
        )}
      </div>
    </Layout>
  );
};

export default WhatsAppIntegrationsPage;
