import React, { useState, useEffect } from 'react';
import { useAuth } from '../contexts/AuthContext';
import './Admin.css';

interface User {
  id: string;
  email: string;
  username: string;
  full_name?: string;
  is_active: boolean;
  is_verified: boolean;
  is_superadmin: boolean;
  created_at: string;
  last_login_at?: string;
}

interface Stats {
  total_users: number;
  active_users: number;
  inactive_users: number;
  total_habits: number;
  total_completions: number;
}

const Admin: React.FC<{ onBack: () => void }> = ({ onBack }) => {
  const { token } = useAuth();
  const [users, setUsers] = useState<User[]>([]);
  const [stats, setStats] = useState<Stats | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [modalType, setModalType] = useState<'password' | 'edit' | null>(null);
  const [newPassword, setNewPassword] = useState('');
  const [editData, setEditData] = useState({
    email: '',
    username: '',
    full_name: ''
  });

  const backendUrl = `${window.location.protocol}//${window.location.host}`;

  useEffect(() => {
    loadData();
  }, []);

  const loadData = async () => {
    try {
      const statsRes = await fetch(`${backendUrl}/api/v1/admin/stats`, {
        headers: { 'Authorization': `Bearer ${token}` }
      });
      if (statsRes.ok) {
        setStats(await statsRes.json());
      }

      const usersRes = await fetch(`${backendUrl}/api/v1/admin/users`, {
        headers: { 'Authorization': `Bearer ${token}` }
      });
      if (usersRes.ok) {
        setUsers(await usersRes.json());
      }
    } catch (error) {
      console.error('Erro ao carregar dados:', error);
    } finally {
      setLoading(false);
    }
  };

  const openEditModal = (user: User) => {
    setSelectedUser(user);
    setEditData({
      email: user.email,
      username: user.username,
      full_name: user.full_name || ''
    });
    setModalType('edit');
  };

  const openPasswordModal = (user: User) => {
    setSelectedUser(user);
    setNewPassword('');
    setModalType('password');
  };

  const updateUser = async () => {
    if (!selectedUser) return;

    try {
      const response = await fetch(`${backendUrl}/api/v1/admin/users/${selectedUser.id}`, {
        method: 'PATCH',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(editData)
      });

      if (response.ok) {
        alert('✅ Usuário atualizado!');
        setModalType(null);
        setSelectedUser(null);
        loadData();
      } else {
        const error = await response.json();
        alert('❌ Erro: ' + (error.detail || 'Erro ao atualizar'));
      }
    } catch (error) {
      console.error('Erro ao atualizar usuário:', error);
      alert('❌ Erro ao atualizar usuário');
    }
  };

  const toggleUserActive = async (userId: string, currentStatus: boolean) => {
    try {
      const response = await fetch(`${backendUrl}/api/v1/admin/users/${userId}`, {
        method: 'PATCH',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ is_active: !currentStatus })
      });

      if (response.ok) {
        loadData();
      }
    } catch (error) {
      console.error('Erro ao atualizar usuário:', error);
    }
  };

  const deleteUser = async (userId: string) => {
    if (!confirm('Tem certeza que deseja desativar este usuário?')) return;

    try {
      const response = await fetch(`${backendUrl}/api/v1/admin/users/${userId}`, {
        method: 'DELETE',
        headers: { 'Authorization': `Bearer ${token}` }
      });

      if (response.ok) {
        loadData();
      }
    } catch (error) {
      console.error('Erro ao deletar usuário:', error);
    }
  };

  const resetPassword = async () => {
    if (!selectedUser) return;
    
    if (!newPassword || newPassword.length < 6) {
      alert('Senha deve ter no mínimo 6 caracteres!');
      return;
    }

    try {
      const response = await fetch(`${backendUrl}/api/v1/admin/users/${selectedUser.id}/reset-password`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ new_password: newPassword })
      });

      if (response.ok) {
        alert('✅ Senha alterada com sucesso!');
        setModalType(null);
        setSelectedUser(null);
        setNewPassword('');
      }
    } catch (error) {
      console.error('Erro ao resetar senha:', error);
    }
  };

  if (loading) {
    return <div className="admin-page"><div className="loading">⏳ Carregando...</div></div>;
  }

  return (
    <div className="admin-page">
      <div className="admin-header">
        <button onClick={onBack} className="back-button">← Voltar</button>
        <h1>👨‍💼 Painel Administrativo</h1>
      </div>

      {stats && (
        <div className="admin-stats">
          <div className="stat-box">
            <div className="stat-icon">👥</div>
            <div className="stat-info">
              <span className="stat-value">{stats.total_users}</span>
              <span className="stat-label">Total Usuários</span>
            </div>
          </div>
          
          <div className="stat-box">
            <div className="stat-icon">✅</div>
            <div className="stat-info">
              <span className="stat-value">{stats.active_users}</span>
              <span className="stat-label">Ativos</span>
            </div>
          </div>
          
          <div className="stat-box">
            <div className="stat-icon">❌</div>
            <div className="stat-info">
              <span className="stat-value">{stats.inactive_users}</span>
              <span className="stat-label">Inativos</span>
            </div>
          </div>
          
          <div className="stat-box">
            <div className="stat-icon">🎯</div>
            <div className="stat-info">
              <span className="stat-value">{stats.total_habits}</span>
              <span className="stat-label">Hábitos</span>
            </div>
          </div>
          
          <div className="stat-box">
            <div className="stat-icon">📊</div>
            <div className="stat-info">
              <span className="stat-value">{stats.total_completions}</span>
              <span className="stat-label">Completions</span>
            </div>
          </div>
        </div>
      )}

      <div className="users-section">
        <h2>👥 Usuários Cadastrados</h2>
        <div className="users-table">
          <table>
            <thead>
              <tr>
                <th>Email</th>
                <th>Username</th>
                <th>Nome</th>
                <th>Status</th>
                <th>Cadastro</th>
                <th>Ações</th>
              </tr>
            </thead>
            <tbody>
              {users.map(user => (
                <tr key={user.id} className={!user.is_active ? 'inactive' : ''}>
                  <td>{user.email}</td>
                  <td>
                    {user.username}
                    {user.is_superadmin && <span className="badge-admin">ADMIN</span>}
                  </td>
                  <td>{user.full_name || '-'}</td>
                  <td>
                    <span className={`status-badge ${user.is_active ? 'active' : 'inactive'}`}>
                      {user.is_active ? 'Ativo' : 'Inativo'}
                    </span>
                  </td>
                  <td>{new Date(user.created_at).toLocaleDateString('pt-BR')}</td>
                  <td className="actions">
                    {!user.is_superadmin && (
                      <>
                        <button 
                          onClick={() => openEditModal(user)}
                          className="btn-edit"
                          title="Editar Usuário"
                        >
                          ✏️
                        </button>
                        
                        <button 
                          onClick={() => toggleUserActive(user.id, user.is_active)}
                          className="btn-toggle"
                          title={user.is_active ? 'Desativar' : 'Ativar'}
                        >
                          {user.is_active ? '🔴' : '🟢'}
                        </button>
                        
                        <button 
                          onClick={() => openPasswordModal(user)}
                          className="btn-password"
                          title="Resetar Senha"
                        >
                          🔑
                        </button>
                        
                        <button 
                          onClick={() => deleteUser(user.id)}
                          className="btn-delete"
                          title="Deletar"
                        >
                          🗑️
                        </button>
                      </>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Modal de Editar Usuário */}
      {modalType === 'edit' && selectedUser && (
        <div className="modal-overlay" onClick={() => setModalType(null)}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()}>
            <h2>✏️ Editar Usuário</h2>
            
            <div className="form-group">
              <label>Email</label>
              <input
                type="email"
                value={editData.email}
                onChange={(e) => setEditData({...editData, email: e.target.value})}
              />
            </div>

            <div className="form-group">
              <label>Username</label>
              <input
                type="text"
                value={editData.username}
                onChange={(e) => setEditData({...editData, username: e.target.value})}
              />
            </div>

            <div className="form-group">
              <label>Nome Completo</label>
              <input
                type="text"
                value={editData.full_name}
                onChange={(e) => setEditData({...editData, full_name: e.target.value})}
              />
            </div>

            <div className="modal-actions">
              <button onClick={() => setModalType(null)} className="btn-cancel">
                Cancelar
              </button>
              <button onClick={updateUser} className="btn-confirm">
                Salvar Alterações
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Modal de Reset de Senha */}
      {modalType === 'password' && selectedUser && (
        <div className="modal-overlay" onClick={() => setModalType(null)}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()}>
            <h2>🔑 Resetar Senha</h2>
            <p>Usuário: <strong>{selectedUser.username}</strong></p>
            
            <div className="form-group">
              <label>Nova Senha</label>
              <input
                type="text"
                value={newPassword}
                onChange={(e) => setNewPassword(e.target.value)}
                placeholder="Mínimo 6 caracteres"
                autoFocus
              />
            </div>

            <div className="modal-actions">
              <button onClick={() => setModalType(null)} className="btn-cancel">
                Cancelar
              </button>
              <button onClick={resetPassword} className="btn-confirm">
                Resetar Senha
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default Admin;
