import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { Search, Edit2, Trash2, CheckCircle, XCircle, Building2, ChevronUp, ChevronDown, RotateCcw } from 'lucide-react';
import { fetchUsers, deleteUser, setVerifiedStatus } from '../api/sysadmin';
import { EditUserModal } from '../components/ui/EditUserModal';
import { OrganizationsModal } from '../components/ui/OrganizationsModal';

export const UsersPage = () => {
  const [users, setUsers] = useState<any[]>([]);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [loading, setLoading] = useState(false);

  // Filters
  const [filters, setFilters] = useState({
    name: '',
    email: '',
    isVerified: 'all', // all | true | false
    sortBy: 'createdAt',
    sortOrder: 'desc'
  });

  // Modals state
  const [editingUser, setEditingUser] = useState<any>(null);
  const [orgUser, setOrgUser] = useState<any>(null);

  const loadUsers = async () => {
    setLoading(true);
    try {
      const payload: any = { page, limit: 10, sortBy: filters.sortBy, sortOrder: filters.sortOrder };
      if (filters.name) payload.name = filters.name;
      if (filters.email) payload.email = filters.email;
      if (filters.isVerified !== 'all') payload.isVerified = filters.isVerified === 'true';

      const res = await fetchUsers(payload);
      setUsers(res.data);
      setTotalPages(res.pages);
    } catch (e) {
      console.error(e);
      alert('Error cargando usuarios');
    }
    setLoading(false);
  };

  useEffect(() => {
    loadUsers();
  }, [page, filters.sortBy, filters.sortOrder, filters.isVerified]);

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

  const handleResetFilters = () => {
    setFilters({
      name: '',
      email: '',
      isVerified: 'all',
      sortBy: 'createdAt',
      sortOrder: 'desc'
    });
    setPage(1);
  };

  // Efecto para recargar si se limpian los filtros manualmente
  useEffect(() => {
    if (filters.name === '' && filters.email === '' && filters.isVerified === 'all' && filters.sortBy === 'createdAt' && filters.sortOrder === 'desc') {
      loadUsers();
    }
  }, [filters]);

  const toggleSort = (field: string) => {
    setFilters(prev => {
      if (prev.sortBy === field) {
        return { ...prev, sortOrder: prev.sortOrder === 'asc' ? 'desc' : 'asc' };
      }
      return { ...prev, sortBy: field, sortOrder: 'asc' };
    });
  };

  const renderSortIcon = (field: string) => {
    if (filters.sortBy !== field) return null;
    return filters.sortOrder === 'asc' ? <ChevronUp size={16} /> : <ChevronDown size={16} />;
  };

  const handleDelete = async (user: any) => {
    if (window.confirm(`¿Estás seguro de que deseas eliminar permanentemente al usuario ${user.email}? Esto fallará si el usuario es dueño de organizaciones.`)) {
      try {
        await deleteUser(user._id);
        alert('Usuario eliminado correctamente');
        loadUsers();
      } catch (e: any) {
        alert(e.response?.data?.message || e.message || 'Error al eliminar');
      }
    }
  };

  const handleToggleVerified = async (user: any) => {
    if (window.confirm(`¿Deseas cambiar el estado de verificación de ${user.email}?`)) {
      try {
        await setVerifiedStatus(user._id, !user.verificated);
        loadUsers();
      } catch (e: any) {
        alert('Error al actualizar estado');
      }
    }
  };

  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' }}>Gestión de Usuarios</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: '200px' }}>
            <label style={{ display: 'block', fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.5rem' }}>Nombre / Apellido</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: '200px' }}>
            <label style={{ display: 'block', fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.5rem' }}>Email</label>
            <input 
              type="text" 
              className="input-glass" 
              placeholder="Buscar por email..." 
              value={filters.email}
              onChange={(e) => setFilters({...filters, email: e.target.value})}
            />
          </div>
          <div style={{ width: '150px' }}>
            <label style={{ display: 'block', fontSize: '0.85rem', color: 'var(--text-muted)', marginBottom: '0.5rem' }}>Verificado</label>
            <select 
              className="input-glass" 
              value={filters.isVerified}
              onChange={(e) => setFilters({...filters, isVerified: 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: '700px' }}>
            <thead>
              <tr>
                <th className="sticky-header sortable-header" onClick={() => toggleSort('name')} style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600', cursor: 'pointer', userSelect: 'none' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>Usuario {renderSortIcon('name')}</div>
                </th>
                <th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600' }}>Contacto</th>
                <th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600' }}>Verificado</th>
                <th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600' }}>Cód. Verif.</th>
                <th className="sticky-header sortable-header" onClick={() => toggleSort('createdAt')} style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600', cursor: 'pointer', userSelect: 'none' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '4px' }}>Registro {renderSortIcon('createdAt')}</div>
                </th>
                <th className="sticky-header" style={{ padding: '1rem', color: 'var(--text-muted)', fontWeight: '600', textAlign: 'right' }}>Acciones</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={5} style={{ padding: '2rem', textAlign: 'center' }}>Cargando...</td></tr>
              ) : users.length === 0 ? (
                <tr><td colSpan={5} style={{ padding: '2rem', textAlign: 'center', color: 'var(--text-muted)' }}>No se encontraron usuarios</td></tr>
              ) : (
                users.map(u => (
                  <tr key={u._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)' }}>{u.firstName} {u.lastName}</div>
                      <div style={{ fontSize: '0.85rem', color: 'var(--text-muted)' }}>{u.email}</div>
                    </td>
                    <td style={{ padding: '1rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>
                      {u.phoneCountryCode && `+${u.phoneCountryCode}`} {u.phoneAreaCode} {u.phoneNumber}
                    </td>
                    <td style={{ padding: '1rem' }}>
                      <button 
                        onClick={() => handleToggleVerified(u)}
                        style={{ background: 'transparent', display: 'flex', alignItems: 'center', gap: '5px', color: u.verificated ? 'var(--success)' : 'var(--warning)', cursor: 'pointer' }}
                      >
                        {u.verificated ? <CheckCircle size={18} /> : <XCircle size={18} />}
                        {u.verificated ? 'Sí' : 'No'}
                      </button>
                    </td>
                    <td style={{ padding: '1rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>
                      {u.verificationCode || '-'}
                    </td>
                    <td style={{ padding: '1rem', fontSize: '0.9rem', color: 'var(--text-muted)' }}>
                      {new Date(u.creationDate).toLocaleDateString()}
                    </td>
                    <td style={{ padding: '1rem', textAlign: 'right' }}>
                      <div style={{ display: 'flex', gap: '10px', justifyContent: 'flex-end' }}>
                        <button className="icon-btn" title="Ver Organizaciones" onClick={() => setOrgUser(u)}><Building2 size={18} /></button>
                        <button className="icon-btn" title="Editar Perfil" onClick={() => setEditingUser(u)}><Edit2 size={18} /></button>
                        <button className="icon-btn danger" title="Eliminar" onClick={() => handleDelete(u)}><Trash2 size={18} /></button>
                      </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;
        }
        .sortable-header:hover {
          background: rgba(255, 255, 255, 0.05);
        }
        .table-row-hover:hover {
          background: rgba(255, 255, 255, 0.02);
        }
        .icon-btn {
          background: rgba(255,255,255,0.05);
          color: var(--text-muted);
          padding: 8px;
          border-radius: 8px;
          transition: all 0.2s;
        }
        .icon-btn:hover {
          background: var(--primary);
          color: white;
        }
        .icon-btn.danger:hover {
          background: var(--danger);
        }
        .btn-secondary {
          background: rgba(255,255,255,0.05);
          color: var(--text-main);
          border: 1px solid var(--glass-border);
          padding: 0.5rem 1rem;
          border-radius: 8px;
          transition: all 0.2s;
        }
        .btn-secondary:hover:not(:disabled) {
          background: rgba(255,255,255,0.1);
        }
        .btn-secondary:disabled {
          opacity: 0.5;
          cursor: not-allowed;
        }
        @media (max-width: 768px) {
          .users-page-container {
            height: auto !important;
            overflow: visible !important;
          }
          .filters-bar form > div {
            flex: 1 1 100% !important;
          }
          .table-scroll-container {
            overflow-x: auto;
          }
        }
      `}} />

      {/* Modals */}
      {editingUser && <EditUserModal user={editingUser} onClose={() => setEditingUser(null)} onSaved={loadUsers} />}
      {orgUser && <OrganizationsModal user={orgUser} onClose={() => setOrgUser(null)} />}
    </motion.div>
  );
};
