import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Search, RotateCcw, CheckCircle, XCircle, Server, ServerOff } from 'lucide-react';
import { fetchWapServers } from '../api/sysadmin';

export const WapServersPage = () => {
  const [servers, setServers] = useState<any[]>([]);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [loading, setLoading] = useState(false);

  // Filters
  const [filters, setFilters] = useState({
    name: '',
    description: '',
    active: 'all', // all | true | false
    countBotsFrom: '',
    countBotsTo: ''
  });

  const loadServers = async () => {
    setLoading(true);
    try {
      const payload: any = { page, limit: 10 };
      if (filters.name) payload.name = filters.name;
      if (filters.description) payload.description = filters.description;
      if (filters.active !== 'all') payload.active = filters.active === 'true';
      if (filters.countBotsFrom) payload.countBotsFrom = parseInt(filters.countBotsFrom, 10);
      if (filters.countBotsTo) payload.countBotsTo = parseInt(filters.countBotsTo, 10);

      const res = await fetchWapServers(payload);
      setServers(res.data);
      setTotalPages(res.pages);
    } catch (e) {
      console.error(e);
      alert('Error cargando servidores WAP');
    }
    setLoading(false);
  };

  useEffect(() => {
    loadServers();
  }, [page, filters.active]);

  const handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    setPage(1);
    loadServers();
  };

  const handleResetFilters = () => {
    setFilters({
      name: '',
      description: '',
      active: 'all',
      countBotsFrom: '',
      countBotsTo: ''
    });
    setPage(1);
  };

  useEffect(() => {
    if (filters.name === '' && filters.description === '' && filters.active === 'all' && filters.countBotsFrom === '' && filters.countBotsTo === '') {
      loadServers();
    }
  }, [filters]);

  return (
    <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} className="animate-fade-in users-page-container" style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1rem', flexShrink: 0 }}>
        <h1 style={{ fontSize: '2rem', fontWeight: '700' }}>Servidores WAP</h1>
      </div>

      {/* Filters Bar */}
      <div className="glass-panel filters-bar" style={{ padding: '1.5rem', marginBottom: '1rem', flexShrink: 0 }}>
        <form onSubmit={handleSearch} style={{ display: 'flex', gap: '1rem', flexWrap: 'wrap', alignItems: 'flex-end' }}>
          <div style={{ flex: '1', minWidth: '150px' }}>
            <label style={{ display: 'block', fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.5rem' }}>Nombre</label>
            <input 
              type="text" 
              className="input-glass" 
              placeholder="Buscar por nombre..." 
              value={filters.name}
              onChange={(e) => setFilters({...filters, name: e.target.value})}
            />
          </div>
          <div style={{ flex: '1', minWidth: '150px' }}>
            <label style={{ display: 'block', fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.5rem' }}>Descripción</label>
            <input 
              type="text" 
              className="input-glass" 
              placeholder="Buscar por descripción..." 
              value={filters.description}
              onChange={(e) => setFilters({...filters, description: e.target.value})}
            />
          </div>
          <div style={{ width: '100px' }}>
            <label style={{ display: 'block', fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.5rem' }}>Bots Min</label>
            <input 
              type="number" 
              className="input-glass" 
              placeholder="Mín..." 
              value={filters.countBotsFrom}
              onChange={(e) => setFilters({...filters, countBotsFrom: e.target.value})}
            />
          </div>
          <div style={{ width: '100px' }}>
            <label style={{ display: 'block', fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.5rem' }}>Bots Max</label>
            <input 
              type="number" 
              className="input-glass" 
              placeholder="Máx..." 
              value={filters.countBotsTo}
              onChange={(e) => setFilters({...filters, countBotsTo: e.target.value})}
            />
          </div>
          <div style={{ width: '120px' }}>
            <label style={{ display: 'block', fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.5rem' }}>Activo</label>
            <select 
              className="input-glass" 
              value={filters.active}
              onChange={(e) => setFilters({...filters, active: e.target.value})}
            >
              <option value="all">Todos</option>
              <option value="true">Sí</option>
              <option value="false">No</option>
            </select>
          </div>
          <div style={{ display: 'flex', gap: '8px' }}>
            <button type="submit" className="btn-primary" style={{ display: 'flex', alignItems: 'center', gap: '8px', height: '100%' }}>
              <Search size={18} /> Buscar
            </button>
            <button type="button" onClick={handleResetFilters} className="btn-secondary" style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '0.75rem', height: '100%' }} title="Limpiar Filtros">
              <RotateCcw size={18} />
            </button>
          </div>
        </form>
      </div>

      {/* Table */}
      <div className="glass-panel" style={{ overflow: 'hidden', display: 'flex', flexDirection: 'column', flex: 1 }}>
        <div style={{ overflow: 'auto', flex: 1 }} className="table-scroll-container">
          <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', minWidth: '800px' }}>
            <thead>
              <tr>
                <th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600' }}>Servidor</th>
                <th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600' }}>Dirección IP</th>
                <th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600', textAlign: 'center' }}>Capacidad</th>
                <th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600', textAlign: 'center' }}>Estado</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={4} style={{ padding: '2rem', textAlign: 'center' }}>Cargando servidores...</td></tr>
              ) : servers.length === 0 ? (
                <tr><td colSpan={4} style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-muted)' }}>No se encontraron servidores WAP</td></tr>
              ) : (
                servers.map(s => (
                  <tr key={s._id} style={{ borderBottom: '1px solid rgba(255,255,255,0.05)', transition: 'background 0.2s' }} className="table-row-hover">
                    <td style={{ padding: '1rem' }}>
                      <div style={{ fontWeight: '600', color: 'var(--text-main)', display: 'flex', alignItems: 'center', gap: '8px' }}>
                        {s.active ? <Server size={16} color="var(--primary)" /> : <ServerOff size={16} color="var(--text-muted)" />}
                        {s.name}
                      </div>
                      <div style={{ fontSize: '0.85rem', color: 'var(--text-muted)', marginTop: '4px' }}>{s.description || 'Sin descripción'}</div>
                    </td>
                    <td style={{ padding: '1rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>
                      <div style={{ marginBottom: '2px' }}><span style={{ color: 'var(--text-main)' }}>IPv4:</span> {s.ipv4 || '-'}</div>
                      <div><span style={{ color: 'var(--text-main)' }}>IPv6:</span> {s.ipv6 || '-'}</div>
                    </td>
                    <td style={{ padding: '1rem', textAlign: 'center' }}>
                      <div style={{ background: 'rgba(255,255,255,0.05)', display: 'inline-block', padding: '4px 12px', borderRadius: '12px', fontSize: '0.9rem', color: s.countBots >= s.maxBots ? 'var(--warning)' : 'var(--text-main)' }}>
                        <strong>{s.countBots}</strong> / {s.maxBots} bots
                      </div>
                    </td>
                    <td style={{ padding: '1rem', textAlign: 'center' }}>
                      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '5px', color: s.active ? 'var(--success)' : 'var(--warning)' }}>
                        {s.active ? <CheckCircle size={16} /> : <XCircle size={16} />}
                        {s.active ? 'Activo' : 'Inactivo'}
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
        
        {/* Pagination */}
        <div className="pagination-bar" style={{ padding: '1rem', borderTop: '1px solid var(--glass-border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexShrink: 0, background: 'rgba(0,0,0,0.2)' }}>
          <span style={{ color: 'var(--text-muted)', fontSize: '0.9rem' }}>Página {page} de {totalPages || 1}</span>
          <div style={{ display: 'flex', gap: '10px' }}>
            <button className="btn-secondary" disabled={page === 1} onClick={() => setPage(p => p - 1)}>Anterior</button>
            <button className="btn-secondary" disabled={page >= totalPages} onClick={() => setPage(p => p + 1)}>Siguiente</button>
          </div>
        </div>
      </div>

      <style dangerouslySetInnerHTML={{__html: `
        .sticky-header {
          position: sticky;
          top: 0;
          z-index: 10;
          background: rgba(10, 10, 15, 0.95);
          backdrop-filter: blur(10px);
          border-bottom: 1px solid var(--glass-border);
          transition: background 0.2s;
        }
        .table-row-hover:hover {
          background: rgba(255, 255, 255, 0.02);
        }
      `}} />
    </motion.div>
  );
};
