import React, { useState } from 'react';
import { motion } from 'framer-motion';
import { X, Save } from 'lucide-react';
import { updateCompany, setCompanyBanned } from '../../api/sysadmin';

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

export const EditCompanyModal: React.FC<EditCompanyModalProps> = ({ company, onClose, onSaved }) => {
  const [formData, setFormData] = useState({
    id: company.id || company._id,
    name: company.name || '',
    description: company.description || '',
    categoryId: company.categoryId || '',
    banned: company.banned || false
  });
  const [saving, setSaving] = useState(false);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setSaving(true);
    try {
      await updateCompany({
        ...formData,
        categoryId: parseInt(formData.categoryId.toString(), 10)
      });
      if (company.banned !== formData.banned) {
        await setCompanyBanned(formData.id, formData.banned);
      }
      alert('Organización actualizada');
      onSaved();
      onClose();
    } catch (err: any) {
      alert(err.response?.data?.message || err.message || 'Error al actualizar');
    }
    setSaving(false);
  };

  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: '500px', padding: '2rem', position: 'relative' }}
      >
        <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' }}>Editar Organización</h2>

        <form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
          <div>
            <label style={{ display: 'block', marginBottom: '0.5rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>Nombre</label>
            <input 
              type="text" 
              className="input-glass" 
              style={{ width: '100%' }}
              value={formData.name}
              onChange={e => setFormData({...formData, name: e.target.value})}
              required
            />
          </div>
          <div>
            <label style={{ display: 'block', marginBottom: '0.5rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>Descripción</label>
            <textarea 
              className="input-glass" 
              style={{ width: '100%', minHeight: '80px', resize: 'vertical' }}
              value={formData.description}
              onChange={e => setFormData({...formData, description: e.target.value})}
            />
          </div>
          <div>
            <label style={{ display: 'block', marginBottom: '0.5rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>Categoría (ID)</label>
            <input 
              type="number" 
              className="input-glass" 
              style={{ width: '100%' }}
              value={formData.categoryId}
              onChange={e => setFormData({...formData, categoryId: e.target.value})}
              required
            />
          </div>

          <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
            <input 
              type="checkbox" 
              id="banned-toggle"
              checked={formData.banned}
              onChange={e => setFormData({...formData, banned: e.target.checked})}
              style={{ width: '18px', height: '18px', cursor: 'pointer' }}
            />
            <label htmlFor="banned-toggle" style={{ fontSize: '0.9rem', color: formData.banned ? 'var(--danger)' : 'var(--text-main)', cursor: 'pointer', userSelect: 'none' }}>
              Organización Baneada
            </label>
          </div>

          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '1rem', marginTop: '1rem' }}>
            <button type="button" onClick={onClose} className="btn-secondary" disabled={saving}>Cancelar</button>
            <button type="submit" className="btn-primary" style={{ display: 'flex', alignItems: 'center', gap: '8px' }} disabled={saving}>
              <Save size={18} /> {saving ? 'Guardando...' : 'Guardar Cambios'}
            </button>
          </div>
        </form>
      </motion.div>
    </div>
  );
};
