import React, { useState, useEffect } from 'react';
import { WebSocketService } from '../services/websocket';
import { ConnectionManager } from './ConnectionManager';
import { GatewayStatus } from '../types/gateway';

export const Dashboard: React.FC = () => {
  const [wsService, setWsService] = useState<WebSocketService | null>(null);
  const [gatewayStatus, setGatewayStatus] = useState<GatewayStatus | null>(null);
  const [isConnected, setIsConnected] = useState(false);

  useEffect(() => {
    const wsUrl = import.meta.env.VITE_WS_URL || 'ws://localhost:3003';
    const service = new WebSocketService(wsUrl);
    setWsService(service);

    service.connect()
      .then(() => {
        setIsConnected(true);
        fetchGatewayStatus();
      })
      .catch(error => {
        console.error('Failed to connect to WebSocket:', error);
        setIsConnected(false);
      });

    // Fetch gateway status every 30 seconds (less frequent)
    const statusInterval = setInterval(fetchGatewayStatus, 30000);

    return () => {
      service.disconnect();
      clearInterval(statusInterval);
    };
  }, []);

  const fetchGatewayStatus = async () => {
    try {
      const apiUrl = import.meta.env.VITE_API_URL || 'http://localhost:3001';
      const response = await fetch(`${apiUrl}/api/status`);
      if (response.ok) {
        const data = await response.json();
        if (data.success) {
          setGatewayStatus(data.data);
        }
      }
    } catch (error) {
      console.error('Failed to fetch gateway status:', error);
    }
  };

  const formatUptime = (seconds: number): string => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);
    return `${hours}h ${minutes}m ${secs}s`;
  };

  if (!wsService) {
    return (
      <div className="min-h-screen bg-gray-100 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">Iniciando Manager...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-100">
      <header className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
          <div className="flex justify-between items-center py-4">
            <h1 className="text-2xl font-bold text-gray-900">WhatsApp Gateway Manager</h1>
            <div className="flex items-center space-x-4">
              <div className={`px-3 py-1 rounded-full text-sm font-medium ${
                isConnected ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
              }`}>
                {isConnected ? 'Conectado' : 'Desconectado'}
              </div>
              <button
                onClick={fetchGatewayStatus}
                className="px-3 py-1 bg-blue-600 text-white rounded-full text-sm font-medium hover:bg-blue-700 transition-colors"
              >
                Actualizar
              </button>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="space-y-8">
          {/* Connection Manager - Panel Principal */}
          <ConnectionManager wsService={wsService} />

          {/* Status Info - Panel Inferior Simplificado */}
          {gatewayStatus && (
            <div className="bg-white rounded-lg shadow p-6">
              <h3 className="text-lg font-semibold mb-4">Estado del Sistema</h3>
              <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
                <div>
                  <div className="text-sm text-gray-500">Estado Gateway</div>
                  <div className="font-medium capitalize">{gatewayStatus.status}</div>
                </div>
                <div>
                  <div className="text-sm text-gray-500">Sesión</div>
                  <div className="font-medium">{gatewayStatus.sessionId}</div>
                </div>
                <div>
                  <div className="text-sm text-gray-500">Tiempo Activo</div>
                  <div className="font-medium">{formatUptime(gatewayStatus.uptime)}</div>
                </div>
                <div>
                  <div className="text-sm text-gray-500">Memoria</div>
                  <div className="font-medium">{(gatewayStatus.memory.heapUsed / 1024 / 1024).toFixed(2)} MB</div>
                </div>
              </div>
            </div>
          )}

          {/* Quick Reference - Panel API Simplificado */}
          <div className="bg-white rounded-lg shadow p-6">
            <h3 className="text-lg font-semibold mb-4">Referencia Rápida API</h3>
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <h4 className="font-medium text-gray-700 mb-2">Envío de Mensajes</h4>
                <div className="space-y-1 text-sm">
                  <div className="font-mono bg-gray-50 p-2 rounded">POST /api/send</div>
                  <div className="font-mono bg-gray-50 p-2 rounded">POST /api/send/bulk</div>
                </div>
              </div>
              <div>
                <h4 className="font-medium text-gray-700 mb-2">Control de Sesión</h4>
                <div className="space-y-1 text-sm">
                  <div className="font-mono bg-gray-50 p-2 rounded">POST /api/session/restart</div>
                  <div className="font-mono bg-gray-50 p-2 rounded">POST /api/session/logout</div>
                  <div className="font-mono bg-gray-50 p-2 rounded">POST /api/token</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
    </div>
  );
};