import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { X, ShieldAlert, ShieldCheck } from 'lucide-react';
import { fetchServices, setServiceBanned } from '../../api/sysadmin';

interface CompanyServicesModalProps {
  company: any;
  onClose: () => void;
}

export const CompanyServicesModal: React.FC<CompanyServicesModalProps> = ({ company, onClose }) => {
  const [services, setServices] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);

  const loadServices = async () => {
    setLoading(true);
    try {
      const res = await fetchServices({ companyId: company.id || company._id, page, limit: 10 });
      setServices(res.data);
      setTotalPages(res.pages);
    } catch (e) {
      console.error(e);
      alert('Error cargando servicios');
    }
    setLoading(false);
  };

  useEffect(() => {
    loadServices();
  }, [page]);

  const handleToggleBanned = async (service: any) => {
    if (window.confirm(`¿Deseas ${service.banned ? 'quitar el ban' : 'banear'} el servicio ${service.name}?`)) {
      try {
        await setServiceBanned(service.id || service._id, !service.banned);
        loadServices();
      } catch (e: any) {
        alert('Error al actualizar el estado del servicio');
      }
    }
  };

  return (
    <div className="modal-overlay" style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, background: 'rgba(0,0,0,0.6)', backdropFilter: 'blur(4px)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100 }}>
      <motion.div 
        initial={{ scale: 0.95, opacity: 0 }}
        animate={{ scale: 1, opacity: 1 }}
        className="glass-panel" 
        style={{ width: '90%', maxWidth: '800px', padding: '2rem', position: 'relative', display: 'flex', flexDirection: 'column', maxHeight: '80vh' }}
      >
        <button onClick={onClose} style={{ position: 'absolute', top: '1rem', right: '1rem', background: 'transparent', color: 'var(--text-muted)' }}>
          <X size={24} />
        </button>

        <h2 style={{ fontSize: '1.5rem', marginBottom: '1.5rem', fontWeight: 'bold' }}>
          Servicios de {company.name}
        </h2>

        <div style={{ overflow: 'auto', flex: 1 }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left' }}>
            <thead style={{ position: 'sticky', top: 0, background: 'rgba(10, 10, 15, 0.95)', zIndex: 1 }}>
              <tr>
                <th style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600' }}>Servicio</th>
                <th style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600' }}>Precio / Duración</th>
                <th style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600', textAlign: 'right' }}>Acciones</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={3} style={{ padding: '2rem', textAlign: 'center' }}>Cargando...</td></tr>
              ) : services.length === 0 ? (
                <tr><td colSpan={3} style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-muted)' }}>No se encontraron servicios</td></tr>
              ) : (
                services.map(s => (
                  <tr key={s.id || s._id} style={{ borderBottom: '1px solid rgba(255,255,255,0.05)' }}>
                    <td style={{ padding: '1rem' }}>
                      <div style={{ fontWeight: '600', color: 'var(--text-main)' }}>{s.name}</div>
                      <div style={{ fontSize: '0.85rem', color: 'var(--text-muted)' }}>{s.description || '-'}</div>
                    </td>
                    <td style={{ padding: '1rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>
                      ${s.price} / {s.length} min
                    </td>
                    <td style={{ padding: '1rem', textAlign: 'right' }}>
                      <button 
                        onClick={() => handleToggleBanned(s)}
                        className="btn-secondary"
                        style={{ display: 'inline-flex', alignItems: 'center', gap: '5px', color: s.banned ? 'var(--danger)' : 'var(--success)', padding: '6px 12px' }}
                      >
                        {s.banned ? <ShieldAlert size={16} /> : <ShieldCheck size={16} />}
                        {s.banned ? 'Baneado' : 'Activo'}
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        <div style={{ padding: '1rem 0 0 0', borderTop: '1px solid var(--glass-border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '1rem' }}>
          <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>

      </motion.div>
    </div>
  );
};
