import { useEffect, useState } from "react";
import { 
  listUsers, 
  createUser, 
  updateUser, 
  deleteUser,
  type AdminUser 
} from "../../api/adminApi";
import { useAuth } from "../../context/AuthContext";

type UserFormData = {
  username: string;
  password: string;
  email: string;
  fullName: string;
  role: "admin" | "user" | "viewer";
};

const emptyForm: UserFormData = {
  username: "",
  password: "",
  email: "",
  fullName: "",
  role: "user",
};

export default function AdminUsers() {
  const { user: currentUser } = useAuth();
  const [users, setUsers] = useState<AdminUser[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  
  // Modal state
  const [showModal, setShowModal] = useState(false);
  const [editingUser, setEditingUser] = useState<AdminUser | null>(null);
  const [formData, setFormData] = useState<UserFormData>(emptyForm);
  const [saving, setSaving] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);

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

  async function loadUsers() {
    setLoading(true);
    setError(null);
    try {
      const data = await listUsers();
      setUsers(data.users);
    } catch (err: any) {
      setError(err.message || "Failed to load users");
    } finally {
      setLoading(false);
    }
  }

  function openCreateModal() {
    setEditingUser(null);
    setFormData(emptyForm);
    setFormError(null);
    setShowModal(true);
  }

  function openEditModal(user: AdminUser) {
    setEditingUser(user);
    setFormData({
      username: user.username,
      password: "",
      email: user.email || "",
      fullName: user.full_name || "",
      role: user.role,
    });
    setFormError(null);
    setShowModal(true);
  }

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setSaving(true);
    setFormError(null);

    try {
      if (editingUser) {
        // Update existing user
        await updateUser(editingUser.id, {
          email: formData.email || undefined,
          fullName: formData.fullName || undefined,
          role: formData.role,
          password: formData.password || undefined,
        });
      } else {
        // Create new user
        if (!formData.username || !formData.password) {
          throw new Error("Username and password are required");
        }
        await createUser({
          username: formData.username,
          password: formData.password,
          email: formData.email || undefined,
          fullName: formData.fullName || undefined,
          role: formData.role,
        });
      }
      
      setShowModal(false);
      loadUsers();
    } catch (err: any) {
      setFormError(err.message || "Failed to save user");
    } finally {
      setSaving(false);
    }
  }

  async function handleToggleActive(user: AdminUser) {
    if (user.id === currentUser?.id) {
      alert("You cannot disable your own account");
      return;
    }
    
    try {
      await updateUser(user.id, { isActive: !user.is_active });
      loadUsers();
    } catch (err: any) {
      setError(err.message || "Failed to update user");
    }
  }

  async function handleDelete(user: AdminUser) {
    if (user.id === currentUser?.id) {
      alert("You cannot delete your own account");
      return;
    }
    
    if (!confirm(`Are you sure you want to delete user "${user.username}"?`)) {
      return;
    }
    
    try {
      await deleteUser(user.id);
      loadUsers();
    } catch (err: any) {
      setError(err.message || "Failed to delete user");
    }
  }

  return (
    <div className="bf-admin-page">
      <div className="bf-admin-header">
        <div>
          <h1>User Management</h1>
          <p className="bf-admin-subtitle">Manage system users and roles</p>
        </div>
        <button className="btn primary" onClick={openCreateModal}>
          + Add User
        </button>
      </div>

      {error && <div className="bf-admin-error">{error}</div>}

      {loading ? (
        <div className="bf-admin-loading">Loading users...</div>
      ) : (
        <div className="bf-admin-card">
          <table className="bf-admin-table">
            <thead>
              <tr>
                <th>Username</th>
                <th>Name</th>
                <th>Email</th>
                <th>Role</th>
                <th>Status</th>
                <th>Last Login</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {users.map((user) => (
                <tr key={user.id} className={!user.is_active ? "bf-admin-row-disabled" : ""}>
                  <td className="bf-admin-cell-username">{user.username}</td>
                  <td>{user.full_name || "—"}</td>
                  <td>{user.email || "—"}</td>
                  <td>
                    <span className={`bf-admin-role-badge bf-admin-role-${user.role}`}>
                      {user.role}
                    </span>
                  </td>
                  <td>
                    <span className={`bf-admin-status-badge ${user.is_active ? "bf-admin-status-active" : "bf-admin-status-inactive"}`}>
                      {user.is_active ? "Active" : "Disabled"}
                    </span>
                  </td>
                  <td className="bf-admin-cell-date">
                    {user.last_login 
                      ? new Date(user.last_login).toLocaleDateString() 
                      : "Never"}
                  </td>
                  <td>
                    <div className="bf-admin-actions">
                      <button 
                        className="bf-admin-action-btn"
                        onClick={() => openEditModal(user)}
                      >
                        Edit
                      </button>
                      <button 
                        className="bf-admin-action-btn"
                        onClick={() => handleToggleActive(user)}
                        disabled={user.id === currentUser?.id}
                      >
                        {user.is_active ? "Disable" : "Enable"}
                      </button>
                      <button 
                        className="bf-admin-action-btn bf-admin-action-danger"
                        onClick={() => handleDelete(user)}
                        disabled={user.id === currentUser?.id}
                      >
                        Delete
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}

      {/* User Modal */}
      {showModal && (
        <div className="bf-admin-modal-backdrop" onClick={() => setShowModal(false)}>
          <div className="bf-admin-modal" onClick={(e) => e.stopPropagation()}>
            <h2>{editingUser ? "Edit User" : "Create User"}</h2>
            
            {formError && <div className="bf-admin-form-error">{formError}</div>}
            
            <form onSubmit={handleSubmit}>
              <div className="bf-admin-form-group">
                <label>Username</label>
                <input
                  type="text"
                  value={formData.username}
                  onChange={(e) => setFormData({ ...formData, username: e.target.value })}
                  disabled={!!editingUser}
                  required={!editingUser}
                />
              </div>
              
              <div className="bf-admin-form-group">
                <label>{editingUser ? "New Password (leave blank to keep)" : "Password"}</label>
                <input
                  type="password"
                  value={formData.password}
                  onChange={(e) => setFormData({ ...formData, password: e.target.value })}
                  required={!editingUser}
                />
              </div>
              
              <div className="bf-admin-form-group">
                <label>Full Name</label>
                <input
                  type="text"
                  value={formData.fullName}
                  onChange={(e) => setFormData({ ...formData, fullName: e.target.value })}
                />
              </div>
              
              <div className="bf-admin-form-group">
                <label>Email</label>
                <input
                  type="email"
                  value={formData.email}
                  onChange={(e) => setFormData({ ...formData, email: e.target.value })}
                />
              </div>
              
              <div className="bf-admin-form-group">
                <label>Role</label>
                <select
                  value={formData.role}
                  onChange={(e) => setFormData({ ...formData, role: e.target.value as any })}
                >
                  <option value="user">User</option>
                  <option value="admin">Admin</option>
                  <option value="viewer">Viewer</option>
                </select>
              </div>
              
              <div className="bf-admin-form-actions">
                <button type="button" className="btn secondary" onClick={() => setShowModal(false)}>
                  Cancel
                </button>
                <button type="submit" className="btn primary" disabled={saving}>
                  {saving ? "Saving..." : (editingUser ? "Update" : "Create")}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
