import React, { useState, useEffect } from 'react';
import { Wifi, WifiOff, CheckCircle, AlertCircle, Clock, RefreshCw } from 'lucide-react';
import { caixaAPIOfficial } from '../utils/CaixaAPIOfficial';

export const CaixaAPIStatus: React.FC = () => {
  const [status, setStatus] = useState<{
    online: boolean;
    metodo: string;
    tempoResposta: number;
    ultimaVerificacao: string;
  } | null>(null);
  const [loading, setLoading] = useState(false);

  const verificarStatus = async () => {
    setLoading(true);
    try {
      const statusAPI = await caixaAPIOfficial.verificarStatusAPI();
      setStatus(statusAPI);
    } catch (error) {
      setStatus({
        online: false,
        metodo: 'erro',
        tempoResposta: 0,
        ultimaVerificacao: new Date().toLocaleString('pt-BR')
      });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    verificarStatus();
    // Verificar status a cada 2 minutos
    const interval = setInterval(verificarStatus, 2 * 60 * 1000);
    return () => clearInterval(interval);
  }, []);

  if (!status) {
    return (
      <div className="bg-white p-4 rounded-lg shadow-md">
        <div className="animate-pulse">
          <div className="h-4 bg-gray-200 rounded w-1/2 mb-2"></div>
          <div className="h-3 bg-gray-200 rounded w-3/4"></div>
        </div>
      </div>
    );
  }

  return (
    <div className={`p-4 rounded-lg shadow-md border-l-4 ${
      status.online 
        ? 'bg-green-50 border-green-500' 
        : 'bg-red-50 border-red-500'
    }`}>
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-3">
          {status.online ? (
            <Wifi className="w-5 h-5 text-green-600" />
          ) : (
            <WifiOff className="w-5 h-5 text-red-600" />
          )}
          
          <div>
            <h3 className="font-semibold text-gray-800">
              API Oficial da Caixa
            </h3>
            <p className={`text-sm ${
              status.online ? 'text-green-600' : 'text-red-600'
            }`}>
              {status.online ? 'Online e Funcionando' : 'Temporariamente Indisponível'}
            </p>
          </div>
        </div>

        <button
          onClick={verificarStatus}
          disabled={loading}
          className={`p-2 rounded-full transition-colors ${
            loading 
              ? 'text-gray-400 cursor-not-allowed' 
              : 'text-gray-600 hover:text-gray-800 hover:bg-gray-100'
          }`}
        >
          <RefreshCw className={`w-4 h-4 ${loading ? 'animate-spin' : ''}`} />
        </button>
      </div>

      <div className="mt-3 grid grid-cols-1 md:grid-cols-3 gap-3">
        <div className="flex items-center gap-2">
          <CheckCircle className="w-4 h-4 text-blue-500" />
          <span className="text-sm text-gray-600">
            Método: {status.metodo || 'N/A'}
          </span>
        </div>

        <div className="flex items-center gap-2">
          <Clock className="w-4 h-4 text-orange-500" />
          <span className="text-sm text-gray-600">
            Resposta: {status.tempoResposta}ms
          </span>
        </div>

        <div className="flex items-center gap-2">
          <AlertCircle className="w-4 h-4 text-purple-500" />
          <span className="text-sm text-gray-600">
            Verificado: {status.ultimaVerificacao}
          </span>
        </div>
      </div>

      {status.online && (
        <div className="mt-3 p-2 bg-green-100 rounded-md">
          <p className="text-xs text-green-800">
            ✅ Conectado à API oficial da Caixa Econômica Federal. 
            Todos os dados são 100% oficiais e atualizados.
          </p>
        </div>
      )}

      {!status.online && (
        <div className="mt-3 p-2 bg-red-100 rounded-md">
          <p className="text-xs text-red-800">
            ⚠️ API oficial temporariamente indisponível. 
            O sistema usará dados de backup ou históricos da Caixa.
          </p>
        </div>
      )}
    </div>
  );
};

export default CaixaAPIStatus;
